diff --git a/.babelrc b/.babelrc
new file mode 100644
index 0000000000..62f98360a4
--- /dev/null
+++ b/.babelrc
@@ -0,0 +1,22 @@
+{
+ "plugins": [
+ [
+ "prismjs",
+ {
+ "languages": ["js", "css", "jsx", "bash", "ts", "markup", "cpp", "c"],
+ "plugins": [],
+ "css": false
+ }
+ ]
+ ],
+ "presets": [
+ [
+ "babel-preset-gatsby",
+ {
+ "targets": {
+ "browsers": ["last 3 versions", "not ie <= 11", "not android 4.4.3"]
+ }
+ }
+ ]
+ ]
+}
diff --git a/.eslintignore b/.eslintignore
index 370461e035..9d06233755 100644
--- a/.eslintignore
+++ b/.eslintignore
@@ -1,2 +1,5 @@
-test
+.cache
public
+docs/
+meetings/
+build/
diff --git a/.eslintrc.js b/.eslintrc.js
index 73a9b7b010..0be709501a 100644
--- a/.eslintrc.js
+++ b/.eslintrc.js
@@ -1,49 +1,95 @@
module.exports = {
- parser: '@typescript-eslint/parser',
- parserOptions: {
- ecmaFeatures: {
- jsx: true,
+ overrides: [
+ {
+ files: ['**/*.{js,jsx}'],
+ extends: ['airbnb', 'prettier'],
+ env: { node: true },
},
- },
- extends: [
- 'airbnb',
- 'plugin:react/recommended',
- 'plugin:@typescript-eslint/recommended',
- 'prettier/@typescript-eslint',
- 'prettier/react',
- 'plugin:prettier/recommended',
- 'plugin:testing-library/recommended',
- ],
- settings: {
- react: {
- version: 'detect',
+ {
+ files: ['**/*.{ts,tsx}'],
+ extends: ['airbnb', 'prettier', 'plugin:@typescript-eslint/recommended'],
+ plugins: ['@typescript-eslint'],
+ env: { browser: true, node: true },
+ parser: '@typescript-eslint/parser',
+ settings: { 'import/resolver': { typescript: {} } },
+ rules: {
+ 'no-use-before-define': 'off',
+ '@typescript-eslint/no-use-before-define': 'warn',
+ 'import/prefer-default-export': 'off',
+ 'import/extensions': 'off',
+ },
+ },
+ {
+ files: ['**/*.tsx'],
+ extends: [
+ 'airbnb/hooks',
+ 'plugin:react/recommended',
+ 'plugin:jsx-a11y/recommended',
+ ],
+ plugins: ['@typescript-eslint', 'react-hooks'],
+ parserOptions: { ecmaFeatures: { jsx: true } },
+ settings: { react: { version: 'detect' } },
+ rules: {
+ 'react/no-unused-prop-types': 'off',
+ 'react/require-default-props': 'off',
+ 'react/jsx-filename-extension': 'off',
+ 'react-hooks/rules-of-hooks': 'error',
+ 'react-hooks/exhaustive-deps': 'warn',
+ 'consistent-return': 'off',
+ 'react/function-component-definition': [
+ 'error',
+ {
+ namedComponents: 'arrow-function',
+ unnamedComponents: 'arrow-function',
+ },
+ ],
+ },
},
- 'import/resolver': {
- typescript: {},
+ {
+ files: [
+ 'test-processor.js',
+ 'test-setup.js',
+ 'test/**/**.{js,jsx,ts,tsx}',
+ '**/**.test.{js,jsx,ts,tsx}',
+ ],
+ extends: ['plugin:testing-library/react'],
+ env: { jest: true, node: true, browser: true },
+ },
+ {
+ files: ['content/**/*.{md,mdx}'],
+ extends: ['plugin:mdx/recommended'],
+ settings: { 'mdx/code-blocks': false },
+ rules: { 'react/jsx-no-undef': 'off' },
+ },
+ {
+ files: [
+ 'content/about/*.{md,mdx}',
+ 'content/download/*.{md,mdx}',
+ 'content/get-involved/*.{md,mdx}',
+ 'content/homepage/*.{md,mdx}',
+ 'content/learn/*.m{md,mdx}',
+ ],
+ settings: { 'mdx/code-blocks': true },
},
- },
- env: {
- browser: true,
- node: true,
- jest: true,
- },
- rules: {
- 'react/no-unused-prop-types': 'off',
- 'react/require-default-props': 'off',
- 'react/jsx-filename-extension': 'off',
- 'react-hooks/rules-of-hooks': 'error',
- 'react-hooks/exhaustive-deps': 'warn',
- 'import/prefer-default-export': 'off',
- 'import/extensions': 'off',
- 'consistent-return': 'off',
- 'react/no-danger': 'off',
- },
- plugins: ['@typescript-eslint', 'react-hooks'],
- overrides: [
{
- files: ['**/*.js'],
+ files: ['content/**/*.{md,mdx}/*.{js,jsx,cjs,mjs,ts,tsx}'],
rules: {
- '@typescript-eslint/no-var-requires': 'off',
+ camelcase: 'off',
+ '@typescript-eslint/no-unused-vars': 'off',
+ 'consistent-return': 'off',
+ 'func-names': 'off',
+ 'import/extensions': 'off',
+ 'import/no-extraneous-dependencies': 'off',
+ 'import/no-unresolved': 'off',
+ 'no-console': 'off',
+ 'no-empty': 'off',
+ 'no-restricted-globals': 'off',
+ 'no-restricted-syntax': 'off',
+ 'no-undef': 'off',
+ 'no-underscore-dangle': 'off',
+ 'no-unused-expressions': 'off',
+ 'no-unused-vars': 'off',
+ 'prefer-promise-reject-errors': 'off',
},
},
],
diff --git a/.firebaserc b/.firebaserc
index 8395f43706..9eb551c78e 100644
--- a/.firebaserc
+++ b/.firebaserc
@@ -1,6 +1,7 @@
{
"projects": {
- "staging": "nodejs-infrastructure"
+ "staging": "nodejs-infrastructure",
+ "default": "nodejs-infrastructure"
},
"targets": {
"nodejs-infrastructure": {
@@ -11,4 +12,4 @@
}
}
}
-}
\ No newline at end of file
+}
diff --git a/.github/ISSUE_TEMPLATE/bug-report.yml b/.github/ISSUE_TEMPLATE/bug-report.yml
new file mode 100644
index 0000000000..1a75d043f9
--- /dev/null
+++ b/.github/ISSUE_TEMPLATE/bug-report.yml
@@ -0,0 +1,50 @@
+name: 🐛 Bug Report For Nodejs Dev Website
+description: Report an issue if something isn't working as expected 🤔.
+labels: [bug]
+body:
+ - type: markdown
+ attributes:
+ value: |
+ Thanks for wanting to report an issue you've found on the nodejs.dev website.
+ Please fill in the template below. If unsure about something, just do as best
+ as you're able. If you are reporting a visual glitch, it will be much easier
+ for us to fix it when you attach a screenshot as well.
+ - type: input
+ attributes:
+ label: 'URL:'
+ description: The URL of the page you are reporting an issue on.
+ placeholder: https://nodejs.dev
+ validations:
+ required: true
+ - type: input
+ attributes:
+ label: 'Browser Name:'
+ description: What kind of browser are you using?
+ placeholder: Chrome
+ validations:
+ required: true
+ - type: input
+ attributes:
+ label: 'Browser Version:'
+ description: What version of browser are you using?
+ placeholder: '103.0.5060.134'
+ validations:
+ required: true
+ - type: input
+ attributes:
+ label: 'Operating System:'
+ description: What operating system are you using
+ (Write it in full, with version number)?
+ placeholder: 'Windows 10, 21H2, 19044.1826'
+ validations:
+ required: true
+ - type: textarea
+ attributes:
+ label: 'How to reproduce the issue:'
+ placeholder: |
+ 1. What I did.
+ 2. What I expected to happen.
+ 3. What I actually got.
+ 4. If possible, images or videos are welcome.
+ validations:
+ required: true
diff --git a/.github/ISSUE_TEMPLATE/bug_report.md b/.github/ISSUE_TEMPLATE/bug_report.md
deleted file mode 100644
index 2e2af80bcd..0000000000
--- a/.github/ISSUE_TEMPLATE/bug_report.md
+++ /dev/null
@@ -1,26 +0,0 @@
----
-name: Bug Report
-about: Report that something isn't working.
-labels: bug
----
-
-## Description
-
-
-
-### Steps to reproduce
-
-
-
-### Expected result
-
-
-
-### Actual result
-
-
-
-### Environment
-
-- OS Version:
-- Browser Version:
diff --git a/.github/ISSUE_TEMPLATE/config.yml b/.github/ISSUE_TEMPLATE/config.yml
new file mode 100644
index 0000000000..60eef11252
--- /dev/null
+++ b/.github/ISSUE_TEMPLATE/config.yml
@@ -0,0 +1,8 @@
+blank_issues_enabled: false
+contact_links:
+ - name: ⁉️ Need help with Node.js?
+ url: https://github.com/nodejs/help/issues/
+ about: File an issue in our help repo.
+ - name: 📗 Node.js API Docs
+ url: https://github.com/nodejs/node/issues/new?assignees=&labels=doc&template=3-api-ref-docs-problem.yml
+ about: Please open an issue in the main Node.js repo.
diff --git a/.github/ISSUE_TEMPLATE/docs.md b/.github/ISSUE_TEMPLATE/docs.md
deleted file mode 100644
index 4584a5dcae..0000000000
--- a/.github/ISSUE_TEMPLATE/docs.md
+++ /dev/null
@@ -1,20 +0,0 @@
----
-name: Documentation
-about: Use this template for making changes in the docs.
-labels: docs
----
-
-# Documentation Is
-
-
-
-- [ ] Missing/Needed
-- [ ] Incorrect
-- [ ] Confusing
-- [ ] Not Sure?
-
-## Please Explain in Detail
-
-
-
-## Your Proposal for Changes
diff --git a/.github/ISSUE_TEMPLATE/feature-request.yml b/.github/ISSUE_TEMPLATE/feature-request.yml
new file mode 100644
index 0000000000..4e02e73b87
--- /dev/null
+++ b/.github/ISSUE_TEMPLATE/feature-request.yml
@@ -0,0 +1,19 @@
+name: 🚀 Feature proposal for the Node.js website
+description: I have a suggestion (and may want to implement it)!
+labels: [enhancement]
+body:
+ - type: markdown
+ attributes:
+ value: |
+ You have an idea how to improve the site? That's awesome!
+ Before submitting, please have a look at the existing issues if there's already
+ something related to your suggestion.
+ - type: textarea
+ attributes:
+ label: 'Enter your suggestions in details:'
+ placeholder: |
+ 1. What I expected to happen.
+ 2. Your reason (if possible, images or videos are welcome).
+ 3. What I plan to do (Optional but better).
+ validations:
+ required: true
diff --git a/.github/ISSUE_TEMPLATE/feature_request.md b/.github/ISSUE_TEMPLATE/feature_request.md
deleted file mode 100644
index 2ae2001677..0000000000
--- a/.github/ISSUE_TEMPLATE/feature_request.md
+++ /dev/null
@@ -1,17 +0,0 @@
----
-name: Feature Request
-about: Suggest a new idea for the project.
-labels: enhancement
----
-
-## Summary
-
-
-
-### Basic example
-
-
-
-### Motivation
-
-
diff --git a/.github/ISSUE_TEMPLATE/i18n.yml b/.github/ISSUE_TEMPLATE/i18n.yml
new file mode 100644
index 0000000000..c7c6c7bed2
--- /dev/null
+++ b/.github/ISSUE_TEMPLATE/i18n.yml
@@ -0,0 +1,18 @@
+name: 🔡 Internationalization and translations For Nodejs Website
+description: Hello. Hola. Salut. Ciao. Здравствуйте. こんにちは.
+labels: [i18n]
+body:
+ - type: markdown
+ attributes:
+ value: |
+ Please mention the relevant localization team in your issue,
+ it helps us having the right people take a look, or if you want
+ to create a new localization team.
+ - type: textarea
+ attributes:
+ label: 'Enter your issue on localizations here:'
+ placeholder: |
+ 1. The name of the team (e.g: nodejs/node-cn).
+ 2. Any problems to report or you want to create it?
+ validations:
+ required: true
diff --git a/.github/PULL_REQUEST_TEMPLATE.md b/.github/PULL_REQUEST_TEMPLATE.md
index a116b2b665..399bb66fff 100644
--- a/.github/PULL_REQUEST_TEMPLATE.md
+++ b/.github/PULL_REQUEST_TEMPLATE.md
@@ -1,5 +1,5 @@
## Description
@@ -13,7 +13,16 @@ Please read the [Code of Conduct](https://github.com/nodejs/nodejs.dev/blob/mast
e.g. Fixes #1234, Addresses #1234, Related to #1234, etc.
-->
+### Check List
+
\ No newline at end of file
+ATTENTION
+Please follow this check list to ensure that you've followed all items before opening this PR
+-->
+
+- [ ] I have read the [Contributing Guidelines](https://github.com/nodejs/nodejs.dev/blob/main/CONTRIBUTING.md) and made commit messages that follow the guideline.
+- [ ] I have run `npm run lint:js -- --fix` and/or `npm run lint:md -- --fix` for my JavaScript and/or Markdown changes.
+ - This is important as most of the cases your code changes might not be correctly linted
+- [ ] I have run `npm run test` to check if all tests are passing, and/or `npm run test -- -u` to update snapshots if I created and/or updated React Components.
+- [ ] I have checked that the build works locally and that `npm run build` work fine.
+- [ ] I've covered new added functionality with unit tests if necessary.
diff --git a/.github/workflows/cleanup-staging.yml b/.github/workflows/cleanup-staging.yml
index 423e73894f..6f2c8679ca 100644
--- a/.github/workflows/cleanup-staging.yml
+++ b/.github/workflows/cleanup-staging.yml
@@ -1,22 +1,28 @@
name: Cleanup staging deploy
on:
- pull_request:
+ pull_request_target:
types: [closed]
+permissions:
+ contents: read
+
jobs:
- build:
+ cleanup-staging:
runs-on: ubuntu-latest
steps:
- - uses: actions/checkout@v2
+ - name: Git Checkout
+ uses: actions/checkout@v3.3.0
+ with:
+ persist-credentials: false
- - name: Setup GCloud
- uses: GoogleCloudPlatform/github-actions/setup-gcloud@master
+ - name: Auth G Cloud
+ uses: 'google-github-actions/auth@v1'
with:
- project_id: ${{ secrets.GCP_PROJECT_ID }}
- service_account_email: ${{ secrets.GCP_SA_EMAIL }}
- service_account_key: ${{ secrets.GCP_SA_KEY }}
- export_default_credentials: true
+ credentials_json: '${{ secrets.FIREBASE_SERVICE_ACCOUNT_NODEJS_INFRASTRUCTURE }}'
+
+ - name: Setup G Cloud
+ uses: google-github-actions/setup-gcloud@v1
- - name: Remove folder from GCS
+ - name: Remove from G Cloud Storage
run: gsutil -m rm -f gs://staging.nodejs.dev/${{ github.event.pull_request.number }}/** || true
diff --git a/.github/workflows/firebase-deployment.yml b/.github/workflows/firebase-deployment.yml
new file mode 100644
index 0000000000..e15b0aca61
--- /dev/null
+++ b/.github/workflows/firebase-deployment.yml
@@ -0,0 +1,41 @@
+name: Deploy to Firebase Production
+
+on:
+ push:
+ branches:
+ - main
+
+jobs:
+ build-and-deploy:
+ runs-on: ubuntu-latest
+ environment:
+ name: firebase
+ url: https://nodejs.dev/
+ steps:
+ - name: Git Checkout
+ uses: actions/checkout@v3.3.0
+ with:
+ ref: main
+
+ - name: Setup Node.js
+ uses: actions/setup-node@v3
+ with:
+ node-version-file: '.nvmrc'
+ cache: 'npm'
+
+ - name: Install NPM packages
+ run: npm ci
+
+ - uses: jongwooo/gatsby-cache@v1.4.1
+ with:
+ key: firebase-deployment-gatsby-ubuntu-latest
+
+ - name: Build Gatsby
+ run: npm run build-ci
+
+ - uses: FirebaseExtended/action-hosting-deploy@v0.7.0
+ with:
+ repoToken: '${{ secrets.GITHUB_TOKEN }}'
+ firebaseServiceAccount: '${{ secrets.FIREBASE_SERVICE_ACCOUNT_NODEJS_INFRASTRUCTURE }}'
+ channelId: live
+ projectId: '${{ secrets.GCP_PROJECT_ID }}'
diff --git a/.github/workflows/gatsby.yml b/.github/workflows/gatsby.yml
deleted file mode 100644
index cac80ffa03..0000000000
--- a/.github/workflows/gatsby.yml
+++ /dev/null
@@ -1,23 +0,0 @@
-name: Gastby build
-
-on: [pull_request]
-
-jobs:
- test-ci:
- runs-on: ubuntu-latest
- steps:
- - uses: actions/checkout@v2
-
- - uses: actions/cache@v1
- with:
- path: ~/.npm
- key: ${{ runner.os }}-node-${{ hashFiles('**/package-lock.json') }}
- restore-keys: |
- ${{ runner.os }}-node-
-
- - name: Install Dependencies
- if: steps.cache.outputs.cache-hit != 'true'
- run: npm ci
-
- - name: Run test and coverage
- run: npm run build-ci
diff --git a/.github/workflows/generate-preview.yml b/.github/workflows/generate-preview.yml
index e63ff856b8..73339d49c3 100644
--- a/.github/workflows/generate-preview.yml
+++ b/.github/workflows/generate-preview.yml
@@ -4,58 +4,71 @@ on:
pull_request_target:
types: [labeled]
+permissions:
+ contents: read
+ pull-requests: write
+
jobs:
- build:
+ generate-preview:
+ environment:
+ name: firebase-staging
+ url: 'https://staging.nodejs.dev/${{ github.event.pull_request.number }}/'
runs-on: ubuntu-latest
if: github.event.label.name == 'create-preview'
steps:
-
- - uses: actions/checkout@v2
+ - name: Git Checkout
+ uses: actions/checkout@v3.3.0
with:
+ persist-credentials: false
ref: ${{ github.event.pull_request.head.sha }}
- - name: Setup GCloud
- uses: GoogleCloudPlatform/github-actions/setup-gcloud@master
+ - name: Auth G Cloud
+ uses: 'google-github-actions/auth@v1'
with:
- project_id: ${{ secrets.GCP_PROJECT_ID }}
- service_account_email: ${{ secrets.GCP_SA_EMAIL }}
- service_account_key: ${{ secrets.GCP_SA_KEY }}
- export_default_credentials: true
+ credentials_json: '${{ secrets.FIREBASE_SERVICE_ACCOUNT_NODEJS_INFRASTRUCTURE }}'
+
+ - name: Setup G Cloud
+ uses: google-github-actions/setup-gcloud@v1
- - name: Remove create-preview label
- uses: actions/github-script@0.9.0
+ - name: Remove the PR Label
+ uses: actions/github-script@v6
with:
github-token: ${{secrets.GITHUB_TOKEN}}
script: |
- github.issues.removeLabel({
+ github.rest.issues.removeLabel({
issue_number: ${{ github.event.pull_request.number }},
owner: context.repo.owner,
repo: context.repo.repo,
name: ['create-preview']
})
- - name: Install Dependencies
+ - name: Setup Node.js
+ uses: actions/setup-node@v3
+ with:
+ node-version-file: '.nvmrc'
+ cache: npm
+
+ - name: Install NPM packages
run: npm ci
- - name: Run Gatsby Build
- run: npm run build-ci
- env:
- PATH_PREFIX: ${{ github.event.pull_request.number }}/
+ - uses: jongwooo/gatsby-cache@v1.4.1
+ with:
+ key: generate-preview-gatsby-ubuntu-latest
- - name: Run Storybook Build
- run: npm run build-storybook
+ - name: Build Gatsby
+ run: npm run build-ci
env:
PATH_PREFIX: ${{ github.event.pull_request.number }}/
- - name: Upload to GCS
+ - name: Upload to G Cloud Storage
run: gsutil -m rsync -R public gs://staging.nodejs.dev/${{ github.event.pull_request.number }}/
- name: Comment on PR
- uses: actions/github-script@0.9.0
+ uses: actions/github-script@v6
with:
github-token: ${{secrets.GITHUB_TOKEN}}
script: |
- github.issues.createComment({
+ github.rest.issues.createComment({
issue_number: ${{ github.event.pull_request.number }},
owner: context.repo.owner,
repo: context.repo.repo,
diff --git a/.github/workflows/github-pages.yml b/.github/workflows/github-pages.yml
new file mode 100644
index 0000000000..da36a44e0a
--- /dev/null
+++ b/.github/workflows/github-pages.yml
@@ -0,0 +1,59 @@
+name: Build and Deploy to GitHub Pages
+
+on:
+ push:
+ branches:
+ - main
+ workflow_dispatch:
+
+jobs:
+ build-and-deploy:
+ permissions:
+ contents: read
+ pages: read
+ runs-on: ubuntu-latest
+ steps:
+ - name: Git Checkout
+ uses: actions/checkout@v3.3.0
+ with:
+ ref: main
+
+ - name: Setup Pages
+ uses: actions/configure-pages@v3
+
+ - name: Setup Node.js
+ uses: actions/setup-node@v3
+ with:
+ node-version-file: '.nvmrc'
+ cache: 'npm'
+
+ - name: Install NPM packages
+ run: npm ci
+
+ - uses: jongwooo/gatsby-cache@v1.4.1
+ with:
+ key: github-pages-gatsby-ubuntu-latest
+
+ - name: Build Gatsby
+ run: npm run build-ci
+ env:
+ PATH_PREFIX: nodejs.dev/
+
+ - name: Upload Website to Pages
+ uses: actions/upload-pages-artifact@v1
+ with:
+ path: './public'
+
+ deploy:
+ permissions:
+ pages: write
+ id-token: write
+ environment:
+ name: github-pages
+ url: ${{ steps.deployment.outputs.page_url }}
+ runs-on: ubuntu-latest
+ needs: build-and-deploy
+ steps:
+ - name: Deploy to GitHub Pages
+ id: deployment
+ uses: actions/deploy-pages@v1
diff --git a/.github/workflows/pull-request.yml b/.github/workflows/pull-request.yml
new file mode 100644
index 0000000000..ca4d3e61fd
--- /dev/null
+++ b/.github/workflows/pull-request.yml
@@ -0,0 +1,66 @@
+name: Pull Request Checks
+
+on:
+ pull_request:
+
+jobs:
+ test-ci:
+ runs-on: ubuntu-latest
+ steps:
+ - name: Git Checkout
+ uses: actions/checkout@v3.3.0
+ with:
+ persist-credentials: false
+
+ - name: Setup Node.js
+ uses: actions/setup-node@v3
+ with:
+ node-version-file: '.nvmrc'
+ cache: npm
+
+ - name: Install NPM packages
+ run: npm ci
+
+ - name: Run Format Check
+ run: npm run format-check
+
+ - name: Run Lint Checker
+ run: npm run lint
+
+ - name: Run Unit Tests
+ run: npm run test-ci
+
+ - name: Upload Code Coverage
+ uses: codecov/codecov-action@v3
+
+ build-ci:
+ needs: test-ci
+ name: Node on ${{ matrix.os }}
+ runs-on: ${{ matrix.os }}
+
+ strategy:
+ fail-fast: false
+ matrix:
+ os: [ubuntu-latest, windows-latest]
+
+ steps:
+ - name: Git Checkout
+ uses: actions/checkout@v3.3.0
+ with:
+ persist-credentials: false
+
+ - name: Setup Node.js
+ uses: actions/setup-node@v3
+ with:
+ node-version-file: '.nvmrc'
+ cache: npm
+
+ - name: Install NPM packages
+ run: npm ci
+
+ - uses: jongwooo/gatsby-cache@v1.4.1
+ with:
+ key: pull-request-gatsby-ubuntu-latest
+
+ - name: Build Gatsby
+ run: npm run build-ci
diff --git a/.github/workflows/repo-maintenance.yml b/.github/workflows/repo-maintenance.yml
new file mode 100644
index 0000000000..c72074a9e6
--- /dev/null
+++ b/.github/workflows/repo-maintenance.yml
@@ -0,0 +1,28 @@
+name: Close inactive Issues/PRs
+
+on:
+ schedule:
+ - cron: '30 1 * * *'
+
+jobs:
+ close-issues:
+ runs-on: ubuntu-latest
+ permissions:
+ issues: write
+ pull-requests: write
+ steps:
+ - uses: actions/stale@v7
+ with:
+ days-before-issue-stale: 60
+ days-before-issue-close: 14
+ stale-issue-label: 'stale'
+ stale-pr-label: 'stale'
+ stale-issue-message: 'This issue is stale because it has been open for 60 days with no activity.'
+ stale-pr-message: 'This pull request is stale because it has been open for 30 days with no activity.'
+ close-issue-message: 'This isseue was closed because it has been inactive for 14 days since being marked as stale.'
+ close-pr-message: 'This pull request was closed because it has been inactive for 14 days since being marked as stale.'
+ days-before-pr-stale: 30
+ days-before-pr-close: 14
+ exempt-draft-pr: true
+ exempt-issue-labels: 'discussion,enhancement,bug,good first issue,help wanted,docs'
+ repo-token: ${{ secrets.GITHUB_TOKEN }}
diff --git a/.github/workflows/sync-api.yml b/.github/workflows/sync-api.yml
new file mode 100644
index 0000000000..db1b76316d
--- /dev/null
+++ b/.github/workflows/sync-api.yml
@@ -0,0 +1,48 @@
+name: Sync API docs
+
+on:
+ schedule:
+ - cron: '0 0 * * *'
+ workflow_dispatch:
+
+jobs:
+ sync-api-docs:
+ runs-on: ubuntu-latest
+ permissions:
+ contents: write
+ steps:
+ - name: Git Checkout
+ uses: actions/checkout@v3.3.0
+ with:
+ ref: main
+ token: ${{ secrets.ACCESS_TOKEN_ACTIONS }}
+
+ - name: Setup Node.js
+ uses: actions/setup-node@v3
+ with:
+ node-version-file: '.nvmrc'
+ cache: 'npm'
+
+ - name: Install NPM packages
+ run: npm ci
+
+ - name: 'Sync API specifications'
+ shell: bash
+ run: |
+ npm run sync-api
+
+ - name: Lint Markdown files
+ run: npm run lint:md
+
+ - uses: jongwooo/gatsby-cache@v1.4.1
+ with:
+ key: sync-api-gatsby-ubuntu-latest
+
+ - name: Build Gatsby
+ run: npm run build-ci
+
+ - name: Commit API changes
+ uses: stefanzweifel/git-auto-commit-action@v4
+ with:
+ commit_message: 'chore(api): sync auto-generated docs'
+ branch: 'main'
diff --git a/.github/workflows/test.yml b/.github/workflows/test.yml
deleted file mode 100644
index 5b225e0e4d..0000000000
--- a/.github/workflows/test.yml
+++ /dev/null
@@ -1,28 +0,0 @@
-name: Test
-
-on: [pull_request]
-
-jobs:
- test-ci:
- runs-on: ubuntu-latest
- steps:
- - uses: actions/checkout@v2
-
- - uses: actions/setup-node@v1
-
- - uses: actions/cache@v1
- with:
- path: ~/.npm
- key: ${{ runner.os }}-node-${{ hashFiles('**/package-lock.json') }}
- restore-keys: |
- ${{ runner.os }}-node-
-
- - name: Install Dependencies
- if: steps.cache.outputs.cache-hit != 'true'
- run: npm ci
-
- - name: Run linting
- run: npm run lint
-
- - name: Run test and coverage
- run: npm run test-ci
diff --git a/.github/workflows/upload-to-staging.yml b/.github/workflows/upload-to-staging.yml
deleted file mode 100644
index b04ae62830..0000000000
--- a/.github/workflows/upload-to-staging.yml
+++ /dev/null
@@ -1,53 +0,0 @@
-name: Upload to staging
-
-on:
- issue_comment:
- types: [created]
-
-jobs:
- build:
- runs-on: ubuntu-latest
- if: github.event.issue.pull_request != null && github.event.comment.body == '/preview'
- steps:
- - uses: actions/checkout@v2
-
- - name: Checkout Git Branch
- run: |
- git fetch origin +refs/pull/${{ github.event.issue.number }}/merge
- git checkout FETCH_HEAD
-
- - name: Setup GCloud
- uses: GoogleCloudPlatform/github-actions/setup-gcloud@master
- with:
- project_id: ${{ secrets.GCP_PROJECT_ID }}
- service_account_email: ${{ secrets.GCP_SA_EMAIL }}
- service_account_key: ${{ secrets.GCP_SA_KEY }}
- export_default_credentials: true
-
- - name: Install Dependencies
- run: npm ci
-
- - name: Run Gatsby Build
- run: npm run build-ci
- env:
- PATH_PREFIX: ${{ github.event.issue.number }}/
-
- - name: Run Storybook Build
- run: npm run build-storybook
- env:
- PATH_PREFIX: ${{ github.event.issue.number }}/
-
- - name: Upload to GCS
- run: gsutil -m rsync -R public gs://staging.nodejs.dev/${{ github.event.issue.number }}/
-
- - name: Comment on PR
- uses: actions/github-script@0.9.0
- with:
- github-token: ${{secrets.GITHUB_TOKEN}}
- script: |
- github.issues.createComment({
- issue_number: context.issue.number,
- owner: context.repo.owner,
- repo: context.repo.repo,
- body: 'Please find a preview at: https://staging.nodejs.dev/${{ github.event.issue.number }}/'
- });
diff --git a/.gitignore b/.gitignore
index b27c5abea8..712e70f185 100644
--- a/.gitignore
+++ b/.gitignore
@@ -8,6 +8,7 @@ yarn-error.log
.DS_Store
build
+# Cache and Local files
.env
.env.production
.firebase/*
@@ -16,3 +17,8 @@ coverage
.history
yarn.lock
.idea/
+.eslintmdcache
+.eslintjscache
+
+# Firebase
+firebase-debug.log
diff --git a/.nvmrc b/.nvmrc
index f599e28b8a..b009dfb9d9 100644
--- a/.nvmrc
+++ b/.nvmrc
@@ -1 +1 @@
-10
+lts/*
diff --git a/.prettierignore b/.prettierignore
index 51703a000c..10919b5aee 100644
--- a/.prettierignore
+++ b/.prettierignore
@@ -1,5 +1,4 @@
.cache/
-.github/
.history/
public/
coverage/
diff --git a/.prettierrc b/.prettierrc
index 5159a26f3b..867a6097ee 100644
--- a/.prettierrc
+++ b/.prettierrc
@@ -7,6 +7,6 @@
"jsxSingleQuote": false,
"trailingComma": "es5",
"bracketSpacing": true,
- "jsxBracketSameLine": false,
+ "bracketSameLine": false,
"arrowParens": "avoid"
}
diff --git a/.remarkrc b/.remarkrc
deleted file mode 100644
index 0602cd1bd6..0000000000
--- a/.remarkrc
+++ /dev/null
@@ -1,8 +0,0 @@
-{
- "plugins": [
- "remark-frontmatter",
- "remark-preset-lint-node",
- ["remark-lint-first-heading-level", false],
- ["remark-lint-maximum-line-length", false]
- ]
-}
diff --git a/.storybook/addons.js b/.storybook/addons.js
deleted file mode 100644
index 6aed412d04..0000000000
--- a/.storybook/addons.js
+++ /dev/null
@@ -1,2 +0,0 @@
-import '@storybook/addon-actions/register';
-import '@storybook/addon-links/register';
diff --git a/.storybook/main.js b/.storybook/main.js
deleted file mode 100644
index 0e93e53140..0000000000
--- a/.storybook/main.js
+++ /dev/null
@@ -1,53 +0,0 @@
-// some config came from https://dev.to/romansorin/integrating-gatsby-tailwind-and-storybook-2cbi
-
-module.exports = {
- stories: ['../stories/**/*.stories.js', '../stories/**/*.stories.tsx'],
- addons: ['@storybook/addon-actions', '@storybook/addon-links'],
- webpackFinal: async config => {
- // Transpile Gatsby module because Gatsby includes un-transpiled ES6 code.
- config.module.rules[0].exclude = [/node_modules\/(?!(gatsby)\/)/];
- // use installed babel-loader which is v8.0-beta (which is meant to work with @babel/core@7)
- config.module.rules[0].use[0].loader = require.resolve('babel-loader');
- // use @babel/preset-react for JSX and env (instead of staged presets)
- config.module.rules[0].use[0].options.presets = [
- require.resolve('@babel/preset-react'),
- require.resolve('@babel/preset-env'),
- ];
- config.module.rules[0].use[0].options.plugins = [
- // use @babel/plugin-proposal-class-properties for class arrow functions
- require.resolve('@babel/plugin-proposal-class-properties'),
- // use babel-plugin-remove-graphql-queries to remove static queries from components when rendering in storybook
- require.resolve('babel-plugin-remove-graphql-queries'),
- ];
- // Prefer Gatsby ES6 entrypoint (module) over commonjs (main) entrypoint
- config.resolve.mainFields = ['browser', 'module', 'main'];
- config.module.rules.push(
- {
- test: /\.(ts|tsx)$/,
- loader: require.resolve('babel-loader'),
- options: {
- presets: [['react-app', { flow: false, typescript: true }]],
-
- plugins: [
- require.resolve('@babel/plugin-proposal-class-properties'),
- // use babel-plugin-remove-graphql-queries to remove static queries from components when rendering in storybook
- require.resolve('babel-plugin-remove-graphql-queries'),
- ],
- },
- },
- {
- test: /\.s[ac]ss$/i,
- use: [
- // Creates `style` nodes from JS strings
- 'style-loader',
- // Translates CSS into CommonJS
- 'css-loader',
- // Compiles Sass to CSS
- 'sass-loader',
- ],
- }
- );
- config.resolve.extensions.push('.ts', '.tsx');
- return config;
- },
-};
diff --git a/.storybook/preview.js b/.storybook/preview.js
deleted file mode 100644
index e5e4e07a41..0000000000
--- a/.storybook/preview.js
+++ /dev/null
@@ -1,20 +0,0 @@
-import { action } from '@storybook/addon-actions';
-
-// Gatsby's Link overrides:
-// Gatsby Link calls the `enqueue` & `hovering` methods on the global variable ___loader.
-// This global object isn't set in storybook context, requiring you to override it to empty functions (no-op),
-// so Gatsby Link doesn't throw any errors.
-global.___loader = {
- enqueue: () => {},
- hovering: () => {},
-};
-
-// __PATH_PREFIX__ is used inside gatsby-link an other various places. For storybook not to crash, you need to set it as well.
-global.__PATH_PREFIX__ = '';
-
-// Navigating through a gatsby app using gatsby-link or any other gatsby component will use the `___navigate` method.
-// In Storybook it makes more sense to log an action than doing an actual navigate. Checkout the actions addon docs for more info: https://github.com/storybookjs/storybook/tree/master/addons/actions.
-
-window.___navigate = pathname => {
- action('NavigateTo:')(pathname);
-};
diff --git a/.stylelintrc.json b/.stylelintrc.json
new file mode 100644
index 0000000000..1c9d147686
--- /dev/null
+++ b/.stylelintrc.json
@@ -0,0 +1,14 @@
+{
+ "extends": ["stylelint-config-recommended-scss"],
+ "plugins": ["stylelint-order", "stylelint-selector-bem-pattern"],
+ "rules": {
+ "order/properties-alphabetical-order": true,
+ "no-descending-specificity": null,
+ "scss/at-extend-no-missing-placeholder": null,
+ "scss/at-import-partial-extension": "always",
+ "selector-pseudo-class-no-unknown": [
+ true,
+ { "ignorePseudoClasses": ["global"] }
+ ]
+ }
+}
diff --git a/ADDING_LEARN_PAGE.md b/ADDING_LEARN_PAGE.md
new file mode 100644
index 0000000000..7869ede467
--- /dev/null
+++ b/ADDING_LEARN_PAGE.md
@@ -0,0 +1,44 @@
+# Documentation RFCs (Request for Comments)
+
+While the Website Redesign working group continues to iterate on site design and content structure, we will use an RFC process to accept and evaluate Node.js documentation contributions in this repo. Once the new site architecture and documentation ingestion flow is finalized, all docs content will be migrated to its final location and this process updated accordingly.
+
+## When you need to follow this process
+
+With the working group iterating on design and content structure, this process is our way of making sure all content gets good feedback and, with approval, eventually finds its way to the right place in the documentation.
+
+You need to follow this process if you intend to make a "substantial" addition or change to the proposed Node.js getting started guides in this repo. What constitutes a "substantial" change evolves based on community norms. Some changes do not require an RFC. These may include reasonably sized re-phasing, reorganizing, or refactoring an existing documentation page.
+
+If you submit a pull request to implement a significant change to the documentation without going through the RFC process, it may be closed with a polite request to submit an RFC first!
+
+## To begin drafting a documentation page:
+
+1. Fork the [nodejs/nodejs.dev repo](https://github.com/nodejs/nodejs.dev) so that you have your own copy of the repository to which you have push access.
+1. Create your documentation file in `content/learn`. Use a reasonable and descriptive name for the file.
+ - If you're writing a simple Markdown file, use an `.md` extension. Otherwise, if you want to incorporate [JSX](https://reactjs.org/docs/introducing-jsx.html) features, save it with an `.mdx` extension.
+1. Copy the metadata from the template below. This metadata defines crucial information such as authors, the title of your documentation page, and more.
+ ```mdx
+ ---
+ title: 'A title for your page'
+ description: 'A short description of your page'
+ authors: your-github-username
+ section: Name of the Section # Available categories are 'Quick Start' and 'Getting Started'
+ category: learn # Leave this as it is
+ ---
+ ```
+1. Edit your file and begin writing out your article. Put care into the details! Please review the proposed [Node.js Voice and Tone Guidelines](https://github.com/nodejs/nodejs.dev/blob/main/style-guide/0001-voice-and-tone.md) before you begin writing.
+1. When you are ready to get some feedback on your article, submit a pull request back to the main nodejs/nodejs.dev repository. As a pull request, the draft will receive feedback from the larger community, and the author should be prepared to revise it in response.
+1. Build consensus on your article by integrating feedback from the community.
+1. Eventually, the Website Redesign Working Group will decide in one of their bi-weekly meetings whether the RFC is a candidate for inclusion on the Node.js website.
+
+### Recommendations
+
+- We recommend you read general Markdown and MDX documentation before you start writing your article.
+- If you're adding code snippets within your article, please run `npm run lint:js` to check if your snippets follow our linting rules.
+- If you're in doubt regarding a specific Node.js API, refer to the [Node.js Docs](https://nodejs.org/en/docs/).
+
+### Acceptance Criteria
+
+RFCs that are candidates for inclusion on the Node.js website will enter a "final comment period" lasting 7 days. The beginning of this period will be signaled with a comment and tag on the RFC's pull request. The RFC can be modified based upon feedback from the community. Significant modifications may trigger a new final comment period. At the close of this review period, the RFC may be:
+
+- **Accepted** at the close of its final comment period. A working group member will merge the RFC's associated pull request, at which point the RFC will become 'active', or;
+- **Rejected** by the Website Redesign working group after public discussion has settled and comments have been made summarizing the rationale for rejection. A member of the working group should then close the RFC's associated pull request.
diff --git a/CODE_OF_CONDUCT.md b/CODE_OF_CONDUCT.md
index f3fe8299df..a6a1712794 100644
--- a/CODE_OF_CONDUCT.md
+++ b/CODE_OF_CONDUCT.md
@@ -2,5 +2,4 @@
The [Node.js Code of Conduct][] applies to this repo.
-[Node.js code of conduct]:
- https://github.com/nodejs/node/blob/master/CODE_OF_CONDUCT.md
+[Node.js code of conduct]: https://github.com/nodejs/node/blob/HEAD/CODE_OF_CONDUCT.md
diff --git a/CONTRIBUTING.md b/CONTRIBUTING.md
index 8a32c5f7ff..2e2f8aa3da 100644
--- a/CONTRIBUTING.md
+++ b/CONTRIBUTING.md
@@ -1,82 +1,147 @@
-# Making changes to nodejs.dev
+# Contributing guide
-## Vocabulary
+Thank you for your interest in contributing to [nodejs.dev](https://nodejs.dev). Before you proceed, briefly go through the following:
+
+ [Code of Conduct](https://github.com/nodejs/node/blob/HEAD/CODE_OF_CONDUCT.md)
+
+* [🚀 Getting started](#-getting-started)
+ * [Vocabulary](#vocabulary)
+ * [📝 Commit message guidelines](#-commit-message-guidelines)
+ * [📜 Pull Request Policy](#-pull-request-policy)
+ * [Before merging](#before-merging)
+ * [When merging](#when-merging)
+ * [Becoming a collaborator](#becoming-a-collaborator)
+ * [🐛 Debugging failing checks](#-debugging-failing-checks)
+ * [Developer's Certificate of Origin 1.1](#developers-certificate-of-origin-11)
+ * [Remarks](#remarks)
+
+## 🚀 Getting started
+
+1. Click the fork button in the top right to clone the [nodejs.dev repo][]
+
+2. Clone your fork using SSH, GitHub CLI, or HTTPS.
+
+ ```bash
+ git clone git@github.com:/nodejs.dev.git # SSH
+ gh repo clone /nodejs.dev # GitHub CLI
+ git clone https://github.com//nodejs.dev.git # HTTPS
+ ```
+
+3. Change into the nodejs.dev directory.
+
+ ```bash
+ cd nodejs.dev
+ ```
+
+4. Create a remote for keeping your fork as well as your local clone up-to-date.
+
+ ```bash
+ git remote add upstream git@github.com:nodejs/nodejs.dev.git
+ ```
+
+5. Create a new branch for your work.
+
+ ```bash
+ git checkout -b name-of-your-branch
+ ```
+
+6. Run the following to install the dependencies and start a local preview of your work.
+
+ ```bash
+ npm install # installs this project's dependencies
+ npm start # starts a preview of your local changes
+ ```
-* A **Contributor** is any individual creating or commenting on an issue or pull request,
- or contributing in some other way.
-* A **Collaborator** is a contributor who has been given write access to the repository.
+7. Perform a merge to sync your current branch with the upstream branch.
-## Commit Guidelines
+ ```bash
+git fetch upstream
+git merge upstream/main
+```
+
+8. Run `npm test` to confirm that tests, linting, and formatting are passing. See [here](#-debugging-failing-checks) to fix failures. Ensure that your tests are passing before making a PR.
+
+```bash
+npm test
+```
+
+9. Once you're happy with your changes, add and commit them to your branch,
+then push the branch to your fork.
+
+ ```bash
+ cd ~/nodejs.dev
+ git add .
+ git commit -m "some message"
+ git push -u origin name-of-your-branch
+ ```
+
+10. Create a Pull Request. See [PR Policy](#-pull-request-policy)
+
+> **Note**: Go through our [Commit](#-commit-message-guidelines) and Pull Request(#-pull-request-policy) guidelines outlined below.
+
+## 📝 Commit message guidelines
This project follows the [Conventional Commits][] specification.
-There is a built-in commit linter. Basic rules:
+Basic rules:
-* Commit messages must be prefixed with the name of the changed subsystem, followed by a colon and a space and start with an imperative verb. Check the output of `git log --oneline files/you/changed` to find out what subsystems your changes touch.
Supported subsystems:
> build, chore, ci, docs, feat, fix, perf, refactor, revert, style, test
* Commit messages **must** start with a capital letter
-* Commit messages **must not** end with a period `.`
-## Collaboration Policy
-
-* All changes must come in a PR
-* All changes must be reviewed by a member of @nodejs/nodejs.dev,
- @nodejs/website, or @nodejs/website-redesign
-* Pull Requests must be open for at least 48 hours unless included in the special exemptions section below
+* Commit messages **must not** end with a period `.`
-### Special Exemptions
+## 📜 Pull Request Policy
-Pull requests seeking to make any of the following changes do not need to wait 24 hours
+### Before merging
-* Errata fixes
-* Infrastructure Maintenance
-* Tests
+* Pull Requests must be open for at least 48 hours.
+ * Pull reuqests might be immediately merged if they contain critical bug fixes, short erratas (e.g. typos from previous PRs) or any critical change that is considered a "showstopper" for the operation of the website.
+ * These kind of PRs should only be done by existing collaborators that have write-access and/or signed-off by administrators/maintainers.
+* There must be no objections after a 48 hour period
+* Tests must be included in Pull Requests for new features or bug fixes. If any test(s) are failing, you are responsible for fixing them.
-## Landing Pull Requests
+Each contribution is accepted only if there is no objection to it by a collaborator. During the review, collaborators may request that a specific contributor who is an expert in a particular area give an "LGTM" before the PR can be merged.
-### Before you can land
+In the case that an objection is raised in a pull request by another collaborator, all collaborators involved should try to arrive at a consensus by addressing the concerns through discussion, compromise, or withdrawal of the proposed change(s).
-* The Status Checks for the test suite must pass
-* There must be at least one sign off
-* There must be no objections after a 48 hour period
+### When merging
-The default for each contribution is that it is accepted once no collaborator has an objection. During review collaborators may also request that a specific contributor who is most versed in a particular area gives a "LGTM" before the PR can be merged.
+* [`squash`][] pull requests made up of multiple commits
-In the case of an objection being raised in a pull request by another collaborator, all involved collaborators should seek to arrive at a consensus by way of addressing concerns being expressed by discussion, compromise on the proposed change, or withdrawal of the proposed change.
+## Vocabulary
-## When Landing
+* A **Contributor** is any individual who creates an issue/PR, comments on an issue/PR
+ or contributes in some other way.
+* A **Collaborator** is a contributor with write access to the repository. See [here](#becoming-a-collaborator) on how to become a collaborator.
-* Do not use merge button
-* [`squash`][] pull-requests made up of multiple commits
-* Land how you like as long as there are no merge commits
+## Becoming a collaborator
-## Getting Started
+* Collaborators must be actively contributing to the project
+* A Pull Request must be opened on the @nodejs/nodejs.dev README file adding the new collaborator to the list (note the order of names)
+* The Pull Request must be approved by at least two members of @nodejs/nodejs.dev, @nodejs/website, or @nodejs/website-redesign
+* The Pull Request must remain open for 72 hours without any objections
-* Fork
-* Clone your fork `git clone git@github.com:/nodejs.dev.git`
-* cd into your project
-* Add the following to your remotes by doing `git remote add upstream git@github.com:nodejs/nodejs.dev.git`
-* Create a new branch for your awesome work `git checkout -b branchname`
-* Commit your work
-* Push to your branch `git push -u origin yourbranch`
-* Make a pull request
+## 🐛 Debugging failing checks
-## Storybook
+* For failing formatting or linting, try running:
-This project uses [Storybook][], a tool which provides a sandbox environment for developing UI components. To generate the Storybook locally:
+ ```bash
+ npm run format
+ ```
-* Run `npm run storybook`
-* Navigate to `localhost:6006`
+* Tests sometimes fail when you add or update HTML. Run the following to update snapshots:
-The production Storybook can be viewed at
+```bash
+npm run update-snapshot
+```
## Developer's Certificate of Origin 1.1
-By making a contribution to this project, I certify that:
+By contributing to this project, I certify that:
* (a) The contribution was created in whole or in part by me and I have the right to
submit it under the open source license indicated in the file; or
@@ -92,6 +157,10 @@ By making a contribution to this project, I certify that:
including my sign-off) is maintained indefinitely and may be redistributed consistent
with this project or the open source license(s) involved.
-[conventional commits]: https://www.conventionalcommits.org/
+## Remarks
+
+If something is missing here, or you feel something is not well described, feel free to open an [issue](https://github.com/nodejs/nodejs.dev/issues) to discuss it.
+
[`squash`]: https://help.github.com/en/articles/about-pull-request-merges#squash-and-merge-your-pull-request-commits
-[Storybook]: https://storybook.js.org/
+[Conventional Commits]: https://www.conventionalcommits.org/
+[nodejs.dev repo]: https://github.com/nodejs/nodejs.dev/fork
diff --git a/ModerationPolicy.md b/ModerationPolicy.md
index d03970b9dc..aaf4ada858 100644
--- a/ModerationPolicy.md
+++ b/ModerationPolicy.md
@@ -2,5 +2,4 @@
The [Node.js Moderation Policy][] applies to this repo.
-[Node.js moderation policy]:
- https://github.com/nodejs/admin/blob/master/Moderation-Policy.md
+[Node.js moderation policy]: https://github.com/nodejs/admin/blob/main/Moderation-Policy.md
diff --git a/OKR.md b/OKR.md
deleted file mode 100644
index 60d5d49f2b..0000000000
--- a/OKR.md
+++ /dev/null
@@ -1,39 +0,0 @@
-# Nodejs.dev Objectives and Key Results
-
-The Nodejs.dev project uses Objectives and Key Results to provide direction and guidance to the work we do, enabling our work and the work of our initiatives to have a north star for us to work towards.
-
-## Key Concepts
-
-OKRs consist of two elements:
-
-* Objectives
- * Objectives are qualitative, ambitious, and memorable definitions of the things we as a committee would like to achieve.
-* Key Results
- * Key Results are a set of metrics by which we can measure progress toward their objectives. Like objectives, they should be ambitious and overestimate what we can accomplish.
-
-### External References
-
-Here are some external references that may help provide further context on OKRs.
-
-* [Guide: Set goals with OKRs](https://rework.withgoogle.com/guides/set-goals-with-okrs/steps/introduction/)
-* [What is OKR?](https://felipecastro.com/en/okr/what-is-okr/)
-* [What Are OKRs? How to Use OKRs for Planning (and Achieving) Your Goals](https://plan.io/blog/what-are-okrs/)
-
-## OKRs (2020 Set 1):
-
-* **Objective:** Continuity of process
-
- * **Key Result:** Staging and CI have each have a published technical administration summary and a how-to guide.
- * **Key Result:** Consider using issue templates to facilitate operations.
-
-* **Objective:** Identify areas of progress and future goals
-
- * **Key Result:** Create a feature roadmap
- * **Key Result:** Track features & priorities in one place (project?)
- * **Key Result:** Make available the top two features in nodejs.org:
- 1. Docs —
- 2. Download —
-
-* **Objective:** Make explicit the channels of interfacing internally and with larger org
- * **Key Result:** Write down implicit team norms
- * **Key Result:** How do we propose and review non-feature changes in PRs?
diff --git a/README.md b/README.md
index c8a688acb4..35f4177fa3 100644
--- a/README.md
+++ b/README.md
@@ -1,12 +1,18 @@
+### Repository Archival Notice ⚠️
+
+This repository is discontinued and archived. Please follow-up the recent announcement [here](https://github.com/nodejs/nodejs.org/discussions/5131) as development continues on the [`nodejs/nodejs.org`](https://github.com/nodejs/nodejs.org) repository.
+
+Thank you all for your contributions over the years!
+
+----------
+
-
+
-
-
Nodejs.dev site built using Gatsby.js with React.js, TypeScript, SCSS, and Remark.
@@ -18,126 +24,30 @@
-
-
+
+
-**You can find the latest [Figma design protype here](https://www.figma.com/file/lOxAGGg5KXb6nwie7zXkz6/NJ---Design-System?node-id=22%3A6086).**
-
-## 🚀 Get Started
+## 🚀 Quick Start
1. **Install dependencies.**
- ```sh
- # install the dependencies
+ ```bash
npm install
```
-1. **Start developing.**
+2. **Start project locally.**
- ```sh
- # "start": "gatsby develop"
+ ```bash
npm start
```
-1. **Open the source code and start editing!**
-
- Your site is now running at `http://localhost:8000`!
-
- *Note: You'll also see a second link: `http://localhost:8000/___graphql`. This is a tool you can use to experiment with querying your data. Learn more about using this tool in the [Gatsby tutorial](https://next.gatsbyjs.org/tutorial/part-five/#introducing-graphiql).*
-
-## 🧐 What's inside?
-
-A quick look at some of the top-level files and directories found in this project.
-
-```console
-.
-├── .github
-├── .storybook
-├── meetings
-├── node_modules
-├── src
-├── stories
-├── style-guide
-├── test
-├── util-node
-├── .editorconfig
-├── .eslintignore
-├── .eslintrc.js
-├── .firebaserc
-├── .gitignore
-├── .nvmrc
-├── .prettierignore
-├── .prettierrc
-├── .remarkrc
-├── cloudbuild-deploy.yaml
-├── CODE_OF_CONDUCT.md
-├── CONTRIBUTING.md
-├── empty.env
-├── firebase.json
-├── gatsby-config.js
-├── gatsby-node.js
-├── LICENSE
-├── ModerationPolicy.md
-├── OKR.md
-├── package-lock.json
-├── package.json
-├── README.md
-├── test-preprocessor.js
-├── test-setup.js
-└── tsconfig.json
-
-```
-
-1. **`.storybook`**: This directory contains configuration files so the [storybook]("https://storybook.js.org/) package works as it should. Storybook is used to build the individual UI components in this project.
-
-2. **`/node_modules`**: The directory where all of the modules of code that your project depends on (npm packages) are automatically installed.
-
-3. **`/src`**: This directory will contain all of the code related to what you will see on the front-end of your site (what you see in the browser), like your site header, or a page template. "Src" is a convention for "source code."
-
-4. **`/stories`**: This directory contains stories for UI components used in this project. You can find out what a story is [here]("https://storybook.js.org/docs/react/get-started/whats-a-story).
-
-5. **`/test`**: Tests for this projects are stored in this directory. This project uses [Jest]("https://jestjs.io/) as it's testing framework.
-
-6. **`/util-node`**: Custom utility functions that require nodeJs to run can be stored in files inside this directory. An example is the create-slug function in the createSlug.js file that generates unique slugs for articles.
-
-7. **`.gitignore`**: This file tells git which files it should not track/not maintain a version history.
+3. **Open the source code and start editing!**
-8. **`.nvmrc`**: NVM configuration so packages work as they should
+## 🙌 Contributing
-9. **`.prettierrc`**: This is a configuration file for a tool called [Prettier](https://prettier.io/), which is a tool to help keep the formatting of your code consistent.
-
-10. **`empty.env`**: Rename to **`.env`** and set your Contentful API key
-
-11. **`gatsby-config.js`**: This is the main configuration file for a Gatsby site. This is where you can specify information about your site (metadata) like the site title and description, which Gatsby plugins you'd like to include, etc. (Check out the [config docs](https://next.gatsbyjs.org/docs/gatsby-config/) for more detail).
-
-12. **`gatsby-node.js`**: This file is where Gatsby expects to find any usage of the [Gatsby node APIs](https://next.gatsbyjs.org/docs/node-apis/) (if any). These allow customization/extension of default Gatsby settings affecting pieces of the site build process.
-
-13. **`LICENSE`**: Gatsby is licensed under the MIT license.
-
-14. **`package-lock.json`** (See `package.json` below, first). This is an automatically generated file based on the exact versions of your npm dependencies that were installed for your project. (You won't change this file directly).
-
-15. **`package.json`**: A manifest file for Node.js projects, which includes things like metadata (the project's name, author, etc.). This manifest is how npm knows which packages to install for your project.
-
-16. **`README.md`**: A text file containing useful reference information about your project.
-
-17. **`tsconfig.json`**: Config file for TypeScript
-
-## 📝 Data Sources
-
-This repository contains no documentation content. Content is pulled from across the Node.js GitHub Org, Contentful, and other data sources and stitched together into a cohesive website.
-
-### src/documentation
-
-The `src/documentation` directory currently contains all the getting started content.
-
-## 🎓 Learning Gatsby
-
-Looking for more guidance? Full documentation for Gatsby lives [on the website](https://next.gatsbyjs.org/). Here are some places to start:
-
-* **For most developers, we recommend starting with our [in-depth tutorial for creating a site with Gatsby](https://next.gatsbyjs.org/tutorial/).** It starts with zero assumptions about your level of ability and walks through every step of the process.
-
-* **To dive straight into code samples head [to our documentation](https://next.gatsbyjs.org/docs/).** In particular, check out the "Guides", API reference, and "Advanced Tutorials" sections in the sidebar.
+Any person who wants to contribute to the initiative is welcome! Please read
+[Contributing Guidelines][], [Project Overview][], and see the [Figma Design][] to join the effort.
## 🏛 Governance
@@ -149,145 +59,163 @@ own [Contributing Guidelines][].
[Meeting notes][] from past meetings are maintained for later reference.
[Query issues for "Meeting"][] to find future meetings.
-### Summary / Current Status
-
-Our current focus is on site development. Development is happening in the [nodejs.dev repo](https://github.com/nodejs/nodejs.dev). This repo continues to be the hub for the redesign initiative.
-
### Team
-Any person who wants to contribute to the initiative is welcome! Please read
-[Contributing Guidelines][] and join the effort 🙌.
-
This repo is managed by the nodejs.dev. Members of the nodejs website team
-also have commiter rights on the repo.
+also have committer rights on the repo.
#### The nodejs.dev team
-* [@ahmadawais](https://github.com/ahmadawais) - Ahmad Awais ⚡️
-* [@alexandrtovmach](https://github.com/alexandrtovmach) - Alexandr Tovmach
-* [@amiller-gh](https://github.com/amiller-gh) - Adam Miller
-* [@argyleink](https://github.com/argyleink) - Adam Argyle
+* [@aymen94](https://github.com/aymen94) - Aymen Naghmouchi
* [@benhalverson](https://github.com/benhalverson) - Ben Halverson
-* [@BeniCheni](https://github.com/BeniCheni) - Benjamin Chen
-* [@codeekage](https://github.com/codeekage) - Abraham Jr. Agiri
* [@darcyclarke](https://github.com/darcyclarke) - Darcy Clarke
-* [@designMoreWeb](https://github.com/designMoreWeb) - Divy Tolia
-* [@imbhargav5](https://github.com/imbhargav5) - Bhargav Ponnapalli
-* [@jonchurch](https://github.com/jonchurch) - Jonathan Church
-* [@kasicka](https://github.com/kasicka) - Zuzana Svetlíková
-* [@keywordnew](https://github.com/keywordnew) - Manil Chowdhury
-* [@LaRuaNa](https://github.com/LaRuaNa) - Onur Laru
-* [@maddhruv](https://github.com/maddhruv) - Dhruv Jain
-* [@mbj36](https://github.com/mbj36) - Mohit kumar Bajoria
+* [@joesepi](https://github.com/joesepi) - Joe Sepi
+* [@manishprivet](https://github.com/manishprivet) - Manish Kumar
* [@MylesBorins](https://github.com/MylesBorins) - Myles Borins
-* [@ogonzal87](https://github.com/ogonzal87) - Oscar Gonzalez
-* [@ollelauribostrom](https://github.com/ollelauribostrom) - Olle Lauri Boström
-* [@pierreneter](https://github.com/pierreneter)
-* [@sagirk](https://github.com/sagirk) - Sagir Khan
-* [@saulonunesdev](https://github.com/saulonunesdev) - Saulo Nunes
-* [@skllcrn](https://github.com/skllcrn) - Christopher
-* [@SMotaal](https://github.com/SMotaal) - Saleh Abdel Motaal
-* [@timothyis](https://github.com/timothyis) - Timothy
-* [@tstreamDOTh](https://github.com/tstreamDOTh) - T Thiyagaraj
-* [@ZYSzys](https://github.com/ZYSzys) - ZYSzys
+* [@ovflowd](https://github.com/ovflowd) - Claudio Wunder
+* [@rodion-arr](https://github.com/rodion-arr) - Rodion Abdurakhimov
+* [@shanpriyan](https://github.com/shanpriyan) - Shanmughapriyan S
+* [@Trott](https://github.com/Trott) - Rich Trott
+
+ Previous Members
+
+ These are previous members that were part of the **Nodejs.dev** Team:
+
+ * [@ahmadawais](https://github.com/ahmadawais) - Ahmad Awais ⚡️
+ * [@alexandrtovmach](https://github.com/alexandrtovmach) - Alexandr Tovmach
+ * [@amiller-gh](https://github.com/amiller-gh) - Adam Miller
+ * [@argyleink](https://github.com/argyleink) - Adam Argyle
+ * [@BeniCheni](https://github.com/BeniCheni) - Benjamin Chen
+ * [@codeekage](https://github.com/codeekage) - Abraham Jr. Agiri
+ * [@designMoreWeb](https://github.com/designMoreWeb) - Divy Tolia
+ * [@imbhargav5](https://github.com/imbhargav5) - Bhargav Ponnapalli
+ * [@jemjam](https://github.com/jemjam) - j'em bones
+ * [@jonchurch](https://github.com/jonchurch) - Jonathan Church
+ * [@kasicka](https://github.com/kasicka) - Zuzana Svetlíková
+ * [@keywordnew](https://github.com/keywordnew) - Manil Chowdhury
+ * [@lancemccluskey](https://github.com/lancemccluskey) - Lance McCluskey
+ * [@LaRuaNa](https://github.com/LaRuaNa) - Onur Laru
+ * [@maddhruv](https://github.com/maddhruv) - Dhruv Jain
+ * [@marcustisater](https://github.com/marcustisater) - Marcus Tisäter
+ * [@mbj36](https://github.com/mbj36) - Mohit kumar Bajoria
+ * [@ogonzal87](https://github.com/ogonzal87) - Oscar Gonzalez
+ * [@ollelauribostrom](https://github.com/ollelauribostrom) - Olle Lauri Boström
+ * [@pierreneter](https://github.com/pierreneter) - Nguyễn J Huỳnh Long
+ * [@sagirk](https://github.com/sagirk) - Sagir Khan
+ * [@saulonunesdev](https://github.com/saulonunesdev) - Saulo Nunes
+ * [@skllcrn](https://github.com/skllcrn) - Christopher
+ * [@SMotaal](https://github.com/SMotaal) - Saleh Abdel Motaal
+ * [@timothyis](https://github.com/timothyis) - Timothy
+ * [@tstreamDOTh](https://github.com/tstreamDOTh) - T Thiyagaraj
+ * [@ZYSzys](https://github.com/ZYSzys) - ZYSzys
+
+
+
#### The Website Redesign Teams
This repo originated as "The Website Redesign" strategic initiative under
-the Node.js Community Community. Below are various teams and people that
+the Node.js Community Committee. Below are various teams and people that
participated in that process.
##### Information Gathering
-* [@amiller-gh](https://github.com/amiller-gh) - **Adam Miller**
-* [@codeekage](https://github.com/codeekage) - **Agiri Abraham JNR**
-* [@darcyclarke](https://github.com/darcyclarke) - **Darcy Clarke**
-* [@maddhruv](https://github.com/maddhruv) - **Dhruv Jain**
-* [@fhemberger](https://github.com/fhemberger) - **Frederic Hemberger**
-* [@JonahMoses](https://github.com/JonahMoses) - **Jonah Moses**
-* [@chowdhurian](https://github.com/chowdhurian) - **Manil Chowdhury**
-* [@oe](https://github.com/oe) - **Olivia Hugger**
-* [@bnb](https://github.com/bnb) - **Tierney Cyren**
-* [@timothyis](https://github.com/timothyis) - **Timothy**
+* [@amiller-gh](https://github.com/amiller-gh) - Adam Miller
+* [@codeekage](https://github.com/codeekage) - Agiri Abraham JNR
+* [@darcyclarke](https://github.com/darcyclarke) - Darcy Clarke
+* [@maddhruv](https://github.com/maddhruv) - Dhruv Jain
+* [@fhemberger](https://github.com/fhemberger) - Frederic Hemberger
+* [@JonahMoses](https://github.com/JonahMoses) - Jonah Moses
+* [@chowdhurian](https://github.com/chowdhurian) - Manil Chowdhury
+* [@oe](https://github.com/oe) - Olivia Hugger
+* [@bnb](https://github.com/bnb) - Tierney Cyren
+* [@timothyis](https://github.com/timothyis) - Timothy
##### IA / UX Planning
-* [@oe](https://github.com/oe) - **Olivia Hugger**
-* [@fhemberger](https://github.com/fhemberger) - **Frederic Hemberger**
-* [@bnb](https://github.com/bnb) - **Tierney Cyren**
-* [@timothyis](https://github.com/timothyis) - **Timothy**
-* [@JonahMoses](https://github.com/JonahMoses) - **Jonah Moses**
-* [@amiller-gh](https://github.com/amiller-gh) - **Adam Miller**
-* [@emilypmendez](https://github.com/emilypmendez) - **Emily Mendez**
-* [@darcyclarke](https://github.com/darcyclarke) - **Darcy Clarke**
-* [@maddhruv](https://github.com/maddhruv) - **Dhruv Jain**
-* [@chowdhurian](https://github.com/chowdhurian) - **Manil Chowdhury**
-* [@codeekage](https://github.com/codeekage) - **Agiri Abraham JNR**
-* [@add1sun](https://github.com/add1sun) - **Addison Berry**
-* [@Qard](https://github.com/Qard) - **Stephen Belanger**
-* [@watilde](https://github.com/watilde) - **Daijiro Wachi**
-* [@tolmasky](https://github.com/tolmasky) - **Francisco Ryan Tolmasky I**
-* [@milapbhojak](https://github.com/milapbhojak) - **Milap Bhojak**
-* [@devamaz](https://github.com/devamaz) - **Ahmad Abdul-Aziz**
+* [@oe](https://github.com/oe) - Olivia Hugger
+* [@fhemberger](https://github.com/fhemberger) - Frederic Hemberger
+* [@bnb](https://github.com/bnb) - Tierney Cyren
+* [@timothyis](https://github.com/timothyis) - Timothy
+* [@JonahMoses](https://github.com/JonahMoses) - Jonah Moses
+* [@amiller-gh](https://github.com/amiller-gh) - Adam Miller
+* [@emilypmendez](https://github.com/emilypmendez) - Emily Mendez
+* [@darcyclarke](https://github.com/darcyclarke) - Darcy Clarke
+* [@maddhruv](https://github.com/maddhruv) - Dhruv Jain
+* [@chowdhurian](https://github.com/chowdhurian) - Manil Chowdhury
+* [@codeekage](https://github.com/codeekage) - Agiri Abraham JNR
+* [@add1sun](https://github.com/add1sun) - Addison Berry
+* [@Qard](https://github.com/Qard) - Stephen Belanger
+* [@watilde](https://github.com/watilde) - Daijiro Wachi
+* [@tolmasky](https://github.com/tolmasky) - Francisco Ryan Tolmasky I
+* [@milapbhojak](https://github.com/milapbhojak) - Milap Bhojak
+* [@devamaz](https://github.com/devamaz) - Ahmad Abdul-Aziz
##### UI Design and Content Creation
-* [@amiller-gh](https://github.com/amiller-gh) - **Adam Miller**
-* [@bnb](https://github.com/bnb) - **Tierney Cyren**
-* [@codeekage](https://github.com/codeekage) - **Agiri Abraham JNR**
-* [@chowdhurian](https://github.com/chowdhurian) - **Manil Chowdhury**
-* [@maddhruv](https://github.com/maddhruv) - **Dhruv Jain**
-* [@milapbhojak](https://github.com/milapbhojak) - **Milap Bhojak**
-* [@tolmasky](https://github.com/tolmasky) - **Francisco Ryan Tolmasky I**
-* [@iNidAName](https://github.com/inidaname) - **Hassaan Sani**
-* [@abedzantout](https://github.com/abedzantout) - **Abdul Rahman Zantout**
-* [@AliObaji](https://github.com/AliObaji) - **Ali Obaji**
-* [@AhmadAwais](https://github.com/AhmadAwais) - **AhmadAwais**
+* [@amiller-gh](https://github.com/amiller-gh) - Adam Miller
+* [@bnb](https://github.com/bnb) - Tierney Cyren
+* [@codeekage](https://github.com/codeekage) - Agiri Abraham JNR
+* [@chowdhurian](https://github.com/chowdhurian) - Manil Chowdhury
+* [@maddhruv](https://github.com/maddhruv) - Dhruv Jain
+* [@milapbhojak](https://github.com/milapbhojak) - Milap Bhojak
+* [@tolmasky](https://github.com/tolmasky) - Francisco Ryan Tolmasky I
+* [@iNidAName](https://github.com/inidaname) - Hassaan Sani
+* [@abedzantout](https://github.com/abedzantout) - Abdul Rahman Zantout
+* [@AliObaji](https://github.com/AliObaji) - Ali Obaji
+* [@AhmadAwais](https://github.com/AhmadAwais) - AhmadAwais
##### Site Development
-* [@abiclub23](https://github.com/abiclub23) - **Abhi Tondepu**
-* [@ajay2507](https://github.com/ajay2507) - **Ajaykumar**
-* [@connorholyday](https://github.com/connorholyday) - **Connor Holyday**
-* [@iceagency-jakecruse](https://github.com/iceagency-jakecruse) - **Jake Cruse**
-* [@iceagency-lukehopkins](https://github.com/iceagency-lukehopkins) - **Luke Hopkins**
-* [@jestho](https://github.com/jestho) - **Jesper Thøgersen**
-* [@jonahmoses](https://github.com/jonahmoses) - **Jonah Moses**
-* [@sagirk](https://github.com/sagirk) - **Sagir Khan**
-* [@ollelauribostrom](https://github.com/ollelauribostrom) - **Olle Lauri Boström**
-* [@belar](https://github.com/Belar) - **Paweł**
-* [@erichodges](https://github.com/erichodges) - **Eric Hodges**
-* [@utkarshbhimte](https://github.com/utkarshbhimte) - **Utkarsh Bhimte**
-* [@lidoravitan](https://github.com/lidoravitan) - **Lidor Avitan**
-* [@mbj36](https://github.com/mbj36) - **Mohit Bajoria**
-* [@zanmarolt](https://github.com/zanmarolt) - **Zan Marolt**
-* [@imbhargav5](https://github.com/imbhargav5) - **Bhargav Ponnapalli**
-* [@mikeattara](https://github.com/mikeattara) - **Mike Perry Y Attara**
-* [@ZYSzys](https://github.com/ZYSzys) - **ZYSzys**
-* [@mrjam2](https://github.com/mrjam2) - **Jamie Burton**
-* [@jamesgeorge007](https://github.com/jamesgeorge007) - **James George**
-* [@Yash-Handa](https://github.com/Yash-Handa) - **Yash Handa**
-* [@iNidAName](https://github.com/inidaname) - **Hassaan Sani**
-* [@abedzantout](https://github.com/abedzantout) - **Abdul Rahman Zantout**
-* [@LaRuaNa](https://github.com/LaRuaNa) - **Onur Laru**
-* [@AhmadAwais](https://github.com/AhmadAwais) - **AhmadAwais**
-* [@BeniCheni](https://github.com/BeniCheni) - **Benjamin Chen**
-* [@kevjin](https://github.com/kevjin) - **Kevin Jin**
-
-## Links
-
-[Community Committee][]
+* [@abiclub23](https://github.com/abiclub23) - Abhi Tondepu
+* [@ajay2507](https://github.com/ajay2507) - Ajaykumar
+* [@connorholyday](https://github.com/connorholyday) - Connor Holyday
+* [@iceagency-jakecruse](https://github.com/iceagency-jakecruse) - Jake Cruse
+* [@iceagency-lukehopkins](https://github.com/iceagency-lukehopkins) - Luke Hopkins
+* [@jestho](https://github.com/jestho) - Jesper Thøgersen
+* [@jonahmoses](https://github.com/jonahmoses) - Jonah Moses
+* [@sagirk](https://github.com/sagirk) - Sagir Khan
+* [@ollelauribostrom](https://github.com/ollelauribostrom) - Olle Lauri Boström
+* [@belar](https://github.com/Belar) - Paweł
+* [@erichodges](https://github.com/erichodges) - Eric Hodges
+* [@utkarshbhimte](https://github.com/utkarshbhimte) - Utkarsh Bhimte
+* [@lidoravitan](https://github.com/lidoravitan) - Lidor Avitan
+* [@mbj36](https://github.com/mbj36) - Mohit Bajoria
+* [@zanmarolt](https://github.com/zanmarolt) - Zan Marolt
+* [@imbhargav5](https://github.com/imbhargav5) - Bhargav Ponnapalli
+* [@mikeattara](https://github.com/mikeattara) - Mike Perry Y Attara
+* [@ZYSzys](https://github.com/ZYSzys) - ZYSzys
+* [@mrjam2](https://github.com/mrjam2) - Jamie Burton
+* [@jamesgeorge007](https://github.com/jamesgeorge007) - James George
+* [@Yash-Handa](https://github.com/Yash-Handa) - Yash Handa
+* [@iNidAName](https://github.com/inidaname) - Hassaan Sani
+* [@abedzantout](https://github.com/abedzantout) - Abdul Rahman Zantout
+* [@LaRuaNa](https://github.com/LaRuaNa) - Onur Laru
+* [@AhmadAwais](https://github.com/AhmadAwais) - AhmadAwais
+* [@BeniCheni](https://github.com/BeniCheni) - Benjamin Chen
+* [@kevjin](https://github.com/kevjin) - Kevin Jin
+
+## 🔗 Links
+
[Code of Conduct][]
+
[Contributing Guidelines][]
+
+[Figma Design][]
+
[Meeting Notes][]
+
+[Project Overview][]
+
[Query issues for "Meeting"][]
-[community committee]: https://github.com/nodejs/community-committee
-[code of conduct]: https://github.com/nodejs/admin/blob/master/CODE_OF_CONDUCT.md
+[code of conduct]: https://github.com/nodejs/admin/blob/main/CODE_OF_CONDUCT.md
[contributing guidelines]: ./CONTRIBUTING.md
+[figma design]: https://www.figma.com/file/lOxAGGg5KXb6nwie7zXkz6/NJ---Design-System?node-id=22%3A6086
[meeting notes]: ./meetings
+[project overview]: ./docs/project-overview.md
[query issues for "meeting"]: https://github.com/nodejs/nodejs.dev/issues?utf8=%E2%9C%93&q=is%3Aissue+is%3Aopen+Meeting+in%3Atitle
diff --git a/TRANSLATING.md b/TRANSLATING.md
new file mode 100644
index 0000000000..6d85aee073
--- /dev/null
+++ b/TRANSLATING.md
@@ -0,0 +1,149 @@
+# Translating Nodejs.dev
+
+This documentation will guide you on how to translate the numerous components and parts of the Nodejs.dev website.
+
+It will also teach you how to update Language metadata and how to enable Languages locally and how to preview your changes.
+
+## Updating Language Metadatas
+
+Currently, the Nodejs.dev website uses I18N metadatas that follow [this plugin](https://github.com/gatsbyjs/themes/tree/master/packages/gatsby-theme-i18n).
+
+You can see the current (and languages we intend to support in the future) by browsing the `src/i18n/config.json` file.
+
+### How the metadata is structured?
+
+The `src/i18n/config.json` file is a JSON file structured by one single Collection (Array) that contains Language metadatas (each Language being one object).
+
+**The structure of each Language is shown as follow:**
+
+```json
+{
+ "code": "de",
+ "localName": "Deutsch",
+ "name": "German",
+ "langDir": "ltr",
+ "dateFormat": "DD.MM.YYYY",
+ "hrefLang": "",
+ "enabled": false
+ }
+```
+
+**The table below explains the functionality of each field:**
+
+| Field | Example Value | Description | Docs |
+|------------|---------------|---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------|-------------------------------------------------------|
+| code | `de` | The ISO-639-1 2-character code of your Language | https://en.wikipedia.org/wiki/List_of_ISO_639-1_codes |
+| localName | `Deutsch` | The name of your Language in your Language | |
+| name | `German` | The name of your Language in English | |
+| langDir | `ltr` | The direction of text on your language. It could be `ltr` (Left-to-right) or `rtl` (Right-to-left) | |
+| dateFormat | `MM-DD-YYYY` | The date format on your regional locale following the ISO-8601 | https://en.wikipedia.org/wiki/ISO_8601 |
+| hreflang | `de` | The 2-character (`de`) or 4-character (`de_AT`) code of your Language. Used my the browser to identify your Language. A two digit code is Country neutral eg.: Portuguese, and a 4 digit code is Country-specific eg.: Brazilian Portuguese | https://hreflang.org/list-of-hreflang-codes/ |
+| enabled | `false` | If the Language is enabled and currently supported by the website. Should only be enabled if both the I18n team and Nodejs.dev team agrees that sufficient content for that page was translated. | |
+
+**Note.:** When testing a Language locally on your installation, please change `enabled: false` to `enabled: true`
+
+## Translating in-App Texts (Translations that are shown in UI Elements/Components)
+
+As you might have noticed, some of the translations/pieces of text from this website, are used directly within UI Components and do not come from Markdown files.
+
+Those are considered in-Component translations. For Nodejs.dev we're using [FormatJS with React-Intl](https://formatjs.io/docs/react-intl/).
+
+In general you don't need to know the technicalities of our Translation System, but if you're curious enough, these are the references for it.
+
+### Where the Translations are stored?
+
+In-Code/In-Component translations are stored within `src/i18n/locales` on a JSON file. The JSON file contains a Dictionary of Key-Value Pairs.
+
+Where the key is the Translation key and the value is the Text to be displayed.
+
+**An example shown below:**
+
+```json
+"app.download.button.title": "Download Node.js"
+```
+
+The example above shows how translating an entry from the Website works, you only need to translate the value, aka in this case, "Download Node.js", the keys need to remain intact.
+
+### Creating/Updating a Locale file
+
+Right now the nodejs.dev website has a `en.json` localy file.
+
+When creating translations or updating translations for other languages, simply edit the JSON file that corresponds to your Language code. For example, `es.json`.
+
+**Note.:** If the file for your Language code doesn't exist yet, please simply create it. If your language is "Deutsch/German" then the file should be named "de.json".
+
+**Note.:** Use the `src/i81n/config.json` file as reference for Language codes.
+
+## Translating Pages
+
+Most of our Pages contents reside within the `content/` folder. Our pages are written with [Markdown](https://www.markdownguide.org/) and [MDX](https://mdxjs.com/). They supercharge your environment by allowing a custom synatx when writting the pages. Think about these Markdown files as a Microsoft Word document but with an extra Syntax for writing text.
+
+Please refer to the Markdown and MDX guides mentioned above if you're struggling with the Syntax or inner-workings of these Idiomatic Languages/Syntaxes.
+
+## Adding Translations of Components
+
+When adding new translations towards a JSON file, we recommend always to add them in the bottom of the file. This allows contributors to easily see changesets, and see the diff between one translation file from another.
+
+**Note.:** We recommend to use a similar pattern when creating translation keys 👀
+
+### Adding React-Intl to a Component
+
+We recommend using [`injectIntl`](https://formatjs.io/docs/react-intl/api/#injectintl-hoc) HOC (High-order-Component) to bundle the `intl` object within your Component.
+
+We also recommend using the [` `](https://formatjs.io/docs/react-intl/components/#formattedmessage) Component when possible, which doesn't require you to use `injectIntl`, as usually `injectIntl` is used when you need to have access to Imperative APIs such as `intl.formatMessage()`.
+
+This method `intl.formatMessage` should usually be used when you need a translated text on a part of the code that is not JSX. For example, within a Component Prop (Common example.: `aria-label`) or somewhere else.
+
+### How to translate a page?
+
+As mentioned above the content of the pages are within the `content/` folder and all the files contain `.md` or `.mdx` extensions. These files support JSX(MDX), Markdown and plain HTML syntax. We of course, recommend not doing plain HTML, only when needed.
+
+To create the same page for your Language, simply create a new file with the same name, and changing the file extension.
+
+**For example, if the file is called `homepage.en.mdx` then for a French language it should become `homepage.fr.mdx`** Remember to always create a new file and not change the original.
+
+### Page Metadata
+
+Each one of these files has a Metadata which is used to define the title, description and the authors of the page. The metadata is written in [YAML](https://yaml.org/).
+
+An example metadata section of one of our pages is shown as below:
+
+```yaml
+---
+title: node.js-community
+displayTitle: Node.js Community
+description: "Node.js has one of the largest, most vibrant and innovative open source communities in the world. Node.js is built, used, and maintained by the community. We believe the community to be at the core of Node.js popularity. Amazing people from every part of the world, with a common interest, collaborate and shape this community."
+authors: ahmadawais, maedahbatool, saqibameen, msaaddev
+category: community
+---
+```
+
+**Note.:** The `title` and `category` fields should never be changed. Please keep that in mind!
+
+It is fine (and recommended) updating the values of `displayTitle` and `description` to your language. The `displayTitle` is the actual title of the page.
+
+Also, we recommend adding your GitHub username on the list of `authors`, by simply adding a command `,` in the end followed by your GitHub username.
+
+## Submitting Changes
+
+When submitting changes, simply create a PR with the content and/or locale and/or metadata changes for the Language you're contributing for.
+
+We also recommend to tag/mention the i18n team, and in specific the [Team responsible for your Language](https://github.com/nodejs/TSC/blob/main/WORKING_GROUPS.md#i18n).
+
+If your Language is not yet enabled, we recommend to enable it in the PR (on the `config.json` file). And before merging your PR the language should be disabled again, if it was disabled before.
+
+You can of course contest that. Also, please refer the general [Contribution Guidelines](CONTRIBUTING.md) before opening a PR.
+
+We also recommend you to run `npm run lint` to see if your changes contain any Linting Errors.
+
+If you have questions, reach out the Nodejs.dev team!
+
+## F.A.Q. and Troubleshooting
+
+#### When I enable my Language on `config.json` it gives an Error
+
+Make sure a Locale (JSON) file for that language also exists within `src/i18n/locales`
+
+#### I enabled the Language but nothing happened
+
+When enabling Languages please restart your Development server.
diff --git a/WRITING_A_BLOG_POST.md b/WRITING_A_BLOG_POST.md
new file mode 100644
index 0000000000..490829fd35
--- /dev/null
+++ b/WRITING_A_BLOG_POST.md
@@ -0,0 +1,32 @@
+### Writing a Blog Post
+
+In order to publish a new blog post, make sure that you added yourself into `src/data/blog/authors.yaml`. That is the GraphQL schema for all the Blog Posts of the Node.js Website Blog.
+
+The current schema supports the following fields:
+
+| Field | Description | Required |
+| ------- | ---------------------------------------------------------------------------------------------------- | -------- |
+| id | Your unique id. In preference it should be your GitHub Username as we resolve the images from there. | Yes |
+| name | Your display name. It could be your full name. | Yes |
+| website | A link to open when someone wants to get to know more about you | No |
+| bio | A short bio about you when people are looking all the posts that you've published before. | No |
+
+All the blog posts should be written inside `content/blog` as only the Markdown files created there will be considered as blog posts. The blog posts support the full MDX (Markdown Extended) syntax.
+
+Every Blog Post should follow the following template:
+
+```markdown
+---
+title: Your Blog Post Title
+blogAuthors: ["your-blog-authors-id", ...]
+category: "your blog category"
+---
+
+Your Markdown Content
+```
+
+* It is important to mention that category is an optional field. Currently only one category is supported. Multiple authors are supported.
+* The name of you blog post should follow the following format `YYYY-MM-DD-your-blog-post-title.md`.
+* When you publish a new blog post, it will be automatically added to the blog posts list. So be mindful when creating a Pull Request.
+* Blog Posts categories are optional. But when provided the category should exist inside `src/data/blog/categories.yaml` otherwise it will fallback to the "name" of the category.
+* If the author id doesn't exist within `src/data/blog/authors.yaml` it will fallback to `Unknown`.
diff --git a/apiUrls.js b/apiUrls.js
new file mode 100644
index 0000000000..fcd49fa3d6
--- /dev/null
+++ b/apiUrls.js
@@ -0,0 +1,12 @@
+module.exports = {
+ apiReleaseContents: releaseVersion =>
+ `https://api.github.com/repos/nodejs/node/contents/doc/api?ref=${releaseVersion}`,
+ nvmTags: 'https://api.github.com/repos/nvm-sh/nvm/tags',
+ nodeReleaseSchedule:
+ 'https://raw.githubusercontent.com/nodejs/Release/main/schedule.json',
+ nodeReleaseData: 'https://nodejs.org/dist/index.json',
+ nodeBannersData:
+ 'https://raw.githubusercontent.com/nodejs/nodejs.org/main/site.json',
+ jsonLink: (fileName, version) =>
+ `https://nodejs.org/docs/latest-${version}.x/api/${fileName}.json`,
+};
diff --git a/cloudbuild-deploy.yaml b/cloudbuild-deploy.yaml
index 2dd5cf1680..f792532b8d 100644
--- a/cloudbuild-deploy.yaml
+++ b/cloudbuild-deploy.yaml
@@ -13,14 +13,12 @@
# to grant publishing access to Cloud Build.)
steps:
- - name: 'node:12'
+ - name: 'node:18'
entrypoint: npm
args: ['ci']
- - name: 'node:12'
+ - name: 'node:16'
entrypoint: npm
args: ['run', 'build']
- - name: 'node:12'
- entrypoint: npm
- args: ['run', 'build-storybook']
- name: 'gcr.io/$PROJECT_ID/firebase'
args: ['deploy', '--project', '$PROJECT_ID', '--only', 'hosting']
+timeout: 1200s
diff --git a/content/about/about.en.md b/content/about/about.en.md
new file mode 100644
index 0000000000..691a6ac730
--- /dev/null
+++ b/content/about/about.en.md
@@ -0,0 +1,70 @@
+---
+title: about
+displayTitle: About
+description: 'About | Node.js'
+authors: XhmikosR, mikeal, fhemberger, Fishrock123, yous, tomgco, tniessen, SMcCandlish, saadq, Trott, Gornstats, piperchester, naoufal, lpinca, j9t, bnoordhuis, harshadsabne, Chris911, benhalverson
+category: about
+---
+
+As an asynchronous event-driven JavaScript runtime, Node.js is designed to build
+scalable network applications. In the following "hello world" example, many
+connections can be handled concurrently. Upon each connection, the callback is
+fired, but if there is no work to be done, Node.js will sleep.
+
+```js
+const http = require('http');
+
+const hostname = '127.0.0.1';
+const port = 3000;
+
+const server = http.createServer((req, res) => {
+ res.statusCode = 200;
+ res.setHeader('Content-Type', 'text/plain');
+ res.end('Hello World');
+});
+
+server.listen(port, hostname, () => {
+ // eslint-disable-next-line no-console
+ console.log(`Server running at http://${hostname}:${port}/`);
+});
+```
+
+This is in contrast to today's more common concurrency model, in which OS threads
+are employed. Thread-based networking is relatively inefficient and very
+difficult to use. Furthermore, users of Node.js are free from worries of
+dead-locking the process, since there are no locks. Almost no function in
+Node.js directly performs I/O, so the process never blocks except when the I/O is performed using
+synchronous methods of Node.js standard library. Because nothing blocks, scalable systems are very
+reasonable to develop in Node.js.
+
+If some of this language is unfamiliar, there is a full article on
+[Blocking vs. Non-Blocking][].
+
+***
+
+Node.js is similar in design to, and influenced by, systems like Ruby's
+[Event Machine][] and Python's [Twisted][]. Node.js takes the event model a bit
+further. It presents an event loop as a runtime construct instead of as a library. In other systems,
+there is always a blocking call to start the event-loop.
+Typically, behavior is defined through callbacks at the beginning of a script, and
+at the end a server is started through a blocking call like `EventMachine::run()`.
+In Node.js, there is no such start-the-event-loop call. Node.js simply enters the event loop after executing the input script. Node.js
+exits the event loop when there are no more callbacks to perform. This behavior
+is like browser JavaScript — the event loop is hidden from the user.
+
+HTTP is a first-class citizen in Node.js, designed with streaming and low
+latency in mind. This makes Node.js well suited for the foundation of a web
+library or framework.
+
+Node.js being designed without threads doesn't mean you can't take
+advantage of multiple cores in your environment. Child processes can be spawned
+by using our [`child_process.fork()`][] API, and are designed to be easy to
+communicate with. Built upon that same interface is the [`cluster`][] module,
+which allows you to share sockets between processes to enable load balancing
+over your cores.
+
+[blocking vs. non-blocking]: /learn/overview-of-blocking-vs-non-blocking/
+[`child_process.fork()`]: /api/child_process/
+[`cluster`]: https://nodejs.org/api/cluster.html
+[event machine]: https://github.com/eventmachine/eventmachine
+[twisted]: https://twistedmatrix.com/trac/
diff --git a/content/about/about.fr.md b/content/about/about.fr.md
new file mode 100644
index 0000000000..53e8c8efc5
--- /dev/null
+++ b/content/about/about.fr.md
@@ -0,0 +1,70 @@
+---
+title: about
+displayTitle: 'À propos'
+description: 'À propos de | Node.js'
+authors: XhmikosR, mikeal, fhemberger, Fishrock123, yous, tomgco, tniessen, SMcCandlish, saadq, Trott, Gornstats, piperchester, naoufal, lpinca, j9t, bnoordhuis, harshadsabne, Chris911, benhalverson, AugustinMauroy
+category: about
+---
+
+En tant que moteur d'exécution JavaScript asynchrone piloté par événements, Node.js est conçu pour construire
+des applications réseau évolutives. Dans l'exemple suivant de "hello world", de nombreuses
+connexions peuvent être traitées simultanément. A chaque connexion, le callback est
+déclenché, mais s'il n'y a pas de travail à faire, Node.js se met en veille.
+
+```js
+const http = require('http');
+
+const hostname = '127.0.0.1';
+const port = 3000;
+
+const server = http.createServer((req, res) => {
+ res.statusCode = 200;
+ res.setHeader('Content-Type', 'text/plain');
+ res.end('Bonjour tout le monde!'); // fin de la réponse http
+});
+
+server.listen(port, hostname, () => {
+ // eslint-disable-next-line no-console
+ console.log(`Le serveur fonctionne à http://${hostname}:${port}/`);
+});
+```
+
+Cela contraste avec le modèle de concurrence le plus courant aujourd'hui, dans lequel les threads de l'OS
+sont utilisés. La mise en réseau fondée sur les threads est relativement inefficace et très difficile à utiliser.
+En outre, les utilisateurs de Node.js n'ont pas à se soucier du blocage du processus,
+puisqu'il n'y a pas de verrous. Presque aucune fonction de
+Node.js n'effectue directement des E/S, de sorte que le processus ne se bloque jamais. Parce que rien ne bloque, les systèmes évolutifs sont très raisonnables à développer en Node.js.
+
+Si certains de ces termes ne vous sont pas familiers, vous trouverez un article complet sur le site suivant
+[Blocage vs. non-blocage][].
+
+---
+
+Node.js est similaire dans sa conception à, et influencé par, des systèmes comme
+l'[Event Machine][] de Ruby et [Twisted][] de Python. Node.js présente une
+[boucle d'événement][] comme une construction d'exécution plutôt que comme
+une bibliothèque. Dans d'autres systèmes, il y a toujours un appel bloquant pour
+démarrer la [boucle d'événement][].
+Typiquement, le comportement est défini par des callbacks au début d'un script, et
+à la fin, un serveur est démarré par un appel bloquant tel que
+`EventMachine::run()`. Dans Node.js, il n'y a pas d'appel bloquant comme "start-the-event-loop".
+Node.js entre simplement dans la boucle d'événement après avoir exécuté le script d'entrée. Node.js
+sort de la boucle d'événement lorsqu'il n'y a plus de callbacks à exécuter. Ce comportement
+est comme le JavaScript du navigateur - la boucle d'événements est cachée à l'utilisateur.
+
+HTTP est un citoyen de première classe dans Node.js, conçu en gardant à l'esprit streaming et faible latence.
+faible latence à l'esprit. Cela rend Node.js bien adapté pour la fondation d'un web
+bibliothèque ou d'un cadre.
+
+Le fait que Node.js soit conçu sans threads ne veut pas dire que vous ne pouvez pas
+profiter de plusieurs cœurs dans votre environnement. Des processus enfants peuvent être créés
+en utilisant notre API [`child_process.fork()`][], et sont conçus pour être faciles à communiquer avec.
+Construit sur cette même interface, le module [`cluster`][],
+qui vous permet de partager des sockets entre les processus pour équilibrer la charge sur les cœurs.
+
+[blocage vs. non-blocage]: https://nodejs.org/en/docs/guides/blocking-vs-non-blocking/
+[event machine]: https://github.com/eventmachine/eventmachine
+[twisted]: https://twistedmatrix.com/trac/
+[`child_process.fork()`]: https://nodejs.org/api/child_process.html#child_process_child_process_fork_modulepath_args_options
+[`cluster`]: https://nodejs.org/api/cluster.html
+[boucle d'événement]: https://nodejs.org/en/docs/guides/event-loop-timers-and-nexttick/
diff --git a/content/about/about.ja.md b/content/about/about.ja.md
new file mode 100644
index 0000000000..8794d90980
--- /dev/null
+++ b/content/about/about.ja.md
@@ -0,0 +1,46 @@
+---
+title: about
+displayTitle: Node.js について
+description: 'Node.js について | Node.js'
+authors: XhmikosR, mikeal, fhemberger, Fishrock123, yous, tomgco, tniessen, SMcCandlish, saadq, Trott, Gornstats, piperchester, naoufal, lpinca, j9t, bnoordhuis, harshadsabne, Chris911, benhalverson, e-jigsaw
+category: about
+---
+
+Node.js は、非同期のイベントドリブン JavaScript ランタイムとして、スケーラブルなネットワークアプリケーションを構築するために設計されています。次の "hello world" の例では、多くの接続を同時に処理できます。接続を並列に処理することができます。各接続の際に、コールバックが呼び出されます。しかし、何もすることがない場合は、Node.js はスリープします。
+
+```js
+const http = require('http');
+
+const hostname = '127.0.0.1';
+const port = 3000;
+
+const server = http.createServer((req, res) => {
+ res.statusCode = 200;
+ res.setHeader('Content-Type', 'text/plain');
+ res.end('こんにちは世界');
+});
+
+server.listen(port, hostname, () => {
+ // eslint-disable-next-line no-console
+ console.log(`Server running at http://${hostname}:${port}/`);
+});
+```
+
+これは、OS のスレッドを採用した、今日の一般的な並行処理モデルとは対照的です。スレッドベースのネットワークは、比較的非効率で、非常に使いにくいものです。さらに、Node.js にはロックがないので、プロセスのデッドロックの心配もありません。Node.js では、直接入出力を行う関数はほとんどなく、Node.js の標準ライブラリの同期メソッドを用いて入出力を行う場合を除き、プロセスがブロックされることはありません。ブロックするものがないため、Node.js でスケーラブルなシステムを開発することは非常に合理的です。
+
+これらの言葉に馴染みのない方は[Blocking vs. Non-Blocking][]を参照ください。
+
+---
+
+Node.js は、Ruby の[Event Machine][]や Python の[Twisted][]のようなシステムとデザインが似ていて、影響を受けています。Node.js は、イベントモデルをもう少し進めて、イベントループをライブラリとしてではなく、ランタイムの一部として組み込まれています。他のシステムでは、イベントループを開始するためのブロッキングコールが常に存在します。一般的に、動作はスクリプトの最初にコールバックを通して定義され、最後に`EventMachine::run()`のようなブロッキングコールを通してサーバが開始されます。Node.js では、入力スクリプトを実行した後、単にイベントループに入るだけです。Node.js は、実行するコールバックがなくなるとイベントループを終了します。この動作はブラウザの JavaScript と同じで、イベントループはユーザから隠蔽されています。
+
+HTTP は Node.js では第一級オブジェクトで、ストリーミングと低遅延を念頭に置いて設計されています。このため、Node.js はウェブライブラリやフレームワークの基盤によく適しています。
+
+Node.js はスレッドなしで設計されていますが、マルチコアを活用できないわけではありません。子プロセスは、[`child_process.fork()`][] API を使って生成することができ、簡単に通信できるように設計されています。その同じインタフェースの上に構築された[`cluster`][]モジュールは、プロセス間でソケットを共有し、コア上でのロードバランシングを可能にします。
+
+[blocking vs. non-blocking]: /learn/overview-of-blocking-vs-non-blocking/
+[`child_process.fork()`]: /api/child_process/
+[`cluster`]: https://nodejs.org/api/cluster.html
+[event loop]: /learn/the-nodejs-event-loop/
+[event machine]: https://github.com/eventmachine/eventmachine
+[twisted]: https://twistedmatrix.com/trac/
diff --git a/content/about/about.pt.md b/content/about/about.pt.md
new file mode 100644
index 0000000000..1c887439e5
--- /dev/null
+++ b/content/about/about.pt.md
@@ -0,0 +1,45 @@
+---
+title: about
+displayTitle: Sobre
+description: 'Sobre | Node.js'
+authors: XhmikosR, mikeal, fhemberger, Fishrock123, yous, tomgco, tniessen, SMcCandlish, saadq, Trott, Gornstats, piperchester, naoufal, lpinca, j9t, bnoordhuis, harshadsabne, Chris911, benhalverson, nazarepiedady
+category: about
+---
+
+Como executor de JavaScript orientado a eventos assíncronos, a Node está desenhada para construir aplicações de rede escaláveis. No seguinte exemplo "hello world" ou "olá mundo" em Português, várias conexões podem ser manipuladas simultaneamente. Sobre cada conexão, uma função de resposta é disparada, mas se não existe nada a ser feito, a Node.js adormecerá.
+
+```js
+const http = require('http');
+
+const hostname = '127.0.0.1';
+const port = 3000;
+
+const server = http.createServer((req, res) => {
+ res.statusCode = 200;
+ res.setHeader('Content-Type', 'text/plain');
+ res.end('Hello World');
+});
+
+server.listen(port, hostname, () => {
+ // eslint-disable-next-line no-console
+ console.log(`Server running at http://${hostname}:${port}/`);
+});
+```
+
+Isto é em contraste ao modelo de concorrência mais comum dos dias de hoje, nos quais a linhas do sistema operacional são empregadas. A transmissão baseada em linha é relativamente ineficiente e muito difícil de usar. Além disto, os utilizadores da Node.js estão livres de preocupações da travagem dormente de processo, já que não existem travagens. Quase nenhuma função na Node.js realiza diretamente o I/O, então o processo nunca bloqueia exceto quando o I/O é realizado usando métodos síncronos da biblioteca padrão da Node.js. Uma vez que nada bloqueia, sistemas escaláveis são muito mais razoáveis de programar na Node.js.
+
+Se alguma desta linguagem é desconhecida, existe um artigo completo sobre [Obstrução vs. Não Obstrução][blocking vs. non-blocking].
+
+***
+
+A Node.js é similar em desenho a, e influenciada por, sistemas de [Máquina de Evento][event machine] da Ruby e [Dobrado][twisted] da Python. A Node.js leva o modelo de evento um pouco mais adiante. Ela apresenta um laço de evento como um construtor de tempo de execução ao invés de uma biblioteca. Em outros sistemas, existe sempre uma chamada de obstrução para iniciar o laço de evento. Normalmente, o comportamento é definido através de funções de resposta no início de um programa, e no final um servidor é iniciado através de uma chamada de obstrução como `EventMachine::run()`. Na Node.js, não existe tal chamada de iniciar o laço de evento. A Node.js simplesmente introduz o laço de evento depois da execução do programa de entrada. A Node.js sai do laço de evento quando não houverem mais funções de resposta a desempenhar. Este comportamento é como a da JavaScript do navegador — o laço de evento é escondido do utilizador.
+
+O HTTP é um cidadão de primeira classe na Node.js, desenhado com o fluxo e latência baixa em mente. Isto torna a Node.js bem adequada para criação de uma biblioteca ou abstração de web.
+
+A Node.js sendo desenhada sem linhas não significa que não podes tirar partido de vários núcleos no teu ambiente. Os processos filhos podem ser gerados usando a nossa API [`child_process.fork()`][], e estão desenhadas para serem fáceis de se comunicar. Construída sobre aquela mesma interface que é o módulo [`cluster`][], o qual permite-te partilhar saídas entre processos para ativar a estabilização de carregamento sobre os teus núcleos.
+
+[blocking vs. non-blocking]: /learn/overview-of-blocking-vs-non-blocking/
+[`child_process.fork()`]: /api/child_process/
+[`cluster`]: https://nodejs.org/api/cluster.html
+[event machine]: https://github.com/eventmachine/eventmachine
+[twisted]: https://twistedmatrix.com/trac/
diff --git a/content/about/branding.en.md b/content/about/branding.en.md
new file mode 100644
index 0000000000..874fde9150
--- /dev/null
+++ b/content/about/branding.en.md
@@ -0,0 +1,163 @@
+---
+title: branding
+displayTitle: Branding of Node.js
+description: 'Branding | Node.js'
+authors: AugustinMauroy, XhmikosR, mikeal, fhemberger, Fishrock123, yous, tomgco, tniessen, SMcCandlish, saadq, Trott, Gornstats, piperchester, naoufal, lpinca, j9t, bnoordhuis, harshadsabne, Chris911, MrJithil
+category: about
+---
+
+Please review the [trademark policy](https://trademark-policy.openjsf.org/) for information about permissible use of Node.js® logos and marks.
+
+## Color
+
+The following colors are the color palette for the Node.js website. And should be used for other documents.
+
+### Brand colors
+
+
+
+### Neutral colors
+
+
+
+### Status colors
+
+**Danger**
+
+
+
+**Warning**
+
+
+
+**Info**
+
+
+
+### Accent colors
+
+**Accent 1**
+
+
+
+**Accent 2**
+
+
+
+## Font
+
+**Font Name**: Open Sans
+
+**Download**: [www.google.com/fonts/specimen/Open+Sans](https://www.google.com/fonts/specimen/Open+Sans)
+
+## Nodejs logos
+
+### Logos with JS hexagon at right
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+### Logos with JS hexagon at bottom
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+## Assets
+
+### Hexagon
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+### JS from Node.js logo
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
diff --git a/content/about/governance.en.md b/content/about/governance.en.md
new file mode 100644
index 0000000000..1fa905eae9
--- /dev/null
+++ b/content/about/governance.en.md
@@ -0,0 +1,36 @@
+---
+title: governance
+displayTitle: Governance
+description: 'Project Governance | Node.js'
+authors: XhmikosR, fhemberger, thefourtheye, ryanmurakami, refack
+category: about
+---
+
+## Consensus Seeking Process
+
+The Node.js project follows a [Consensus Seeking][] decision making model.
+
+## Collaborators
+
+The [nodejs/node][] core GitHub repository is maintained by the Collaborators
+who are added by the Technical Steering Committee ([TSC][]) on an ongoing basis.
+
+Individuals making significant and valuable contributions are made Collaborators
+and given commit-access to the project. These individuals are identified by the
+TSC and their nomination is discussed with the existing Collaborators.
+
+For the current list of Collaborators, see the project's [README.md][].
+
+A guide for Collaborators is maintained at [collaborator-guide.md][].
+
+## Top Level Committees
+
+The project is governed by the [Technical Steering Committee (TSC)][]
+which is responsible for high-level guidance of the project.
+
+[consensus seeking]: https://en.wikipedia.org/wiki/Consensus-seeking_decision-making
+[readme.md]: https://github.com/nodejs/node/blob/main/README.md#current-project-team-members
+[tsc]: https://github.com/nodejs/TSC
+[technical steering committee (tsc)]: https://github.com/nodejs/TSC/blob/main/TSC-Charter.md
+[collaborator-guide.md]: https://github.com/nodejs/node/blob/main/doc/contributing/collaborator-guide.md
+[nodejs/node]: https://github.com/nodejs/node
diff --git a/content/about/governance.fr.md b/content/about/governance.fr.md
new file mode 100644
index 0000000000..336e809c40
--- /dev/null
+++ b/content/about/governance.fr.md
@@ -0,0 +1,37 @@
+---
+title: governance
+displayTitle: Gouvernance de projet
+description: 'Gouvernance de projet | Node.js'
+authors: XhmikosR, fhemberger, thefourtheye, ryanmurakami, refack, AugustinMauroy
+category: governance
+---
+
+## Processus de recherche de consensus
+
+Le projet Node.js suit un modèle de prise de décision de type [recherche de consensus][].
+
+## Collaborateurs
+
+Le dépôt GitHub de principal [nodejs/node][] est maintenu par les collaborateurs
+qui sont ajoutés par le comité directeur technique ([TSC][]) au fur et à mesure ou
+de manière continue.
+
+Les personnes apportant des contributions significatives et précieuses sont nommées Collaborateurs
+et reçoivent un accès commit au projet. Ces personnes sont identifiées par le
+TSC et leur nomination est discutée avec les collaborateurs existants.
+
+Pour la liste actuelle des collaborateurs, voir le [README.md][] du projet.
+
+Un guide pour les collaborateurs est maintenu à [collaborator-guide.md][].
+
+## Comités de haut niveau
+
+Le projet est dirigé par le [Comité directeur technique (TSC)][]
+qui est responsable de l'orientation de haut niveau du projet
+
+[recherche de consensus]: https://en.wikipedia.org/wiki/Consensus-seeking_decision-making
+[readme.md]: https://github.com/nodejs/node/blob/main/README.md#current-project-team-members
+[tsc]: https://github.com/nodejs/TSC
+[comité directeur technique (tsc)]: https://github.com/nodejs/TSC/blob/main/TSC-Charter.md
+[collaborator-guide.md]: https://github.com/nodejs/node/blob/main/doc/contributing/collaborator-guide.md
+[nodejs/node]: https://github.com/nodejs/node
diff --git a/content/about/governance.pt.md b/content/about/governance.pt.md
new file mode 100644
index 0000000000..05835f3b0b
--- /dev/null
+++ b/content/about/governance.pt.md
@@ -0,0 +1,32 @@
+---
+title: governance
+displayTitle: Governação
+description: 'Governação do Projeto | Node.js'
+authors: XhmikosR, fhemberger, thefourtheye, ryanmurakami, refack, nazarepiedady
+category: about
+---
+
+## Processo de Procura de Consenso
+
+O projeto da Node.js segue um modelo de tomada de decisão conhecido como [Procura de Consenso][consensus seeking].
+
+## Colaboradores
+
+O repositório principal [nodejs/node][] da GitHub é mantido pelos Colaboradores que são adicionados pela Comissão Diretiva Técnica ([TSC, sigla em Inglês][tsc]) sobre uma base em curso.
+
+Os indivíduos fazendo contribuições significantes e valiosas são feitos Colaboradores e dado acesso de envio ao projeto. Estes indivíduos são identificados pela TSC e suas nomeações são discutidas com os Colaboradores existentes.
+
+Para ter a atual lista de Colaboradores, consulte o [README.md][] do projeto.
+
+Um guia para os Colaboradores é mantido no [collaborator-guide.md][].
+
+## Comissões de Alto Nível
+
+O projeto é governado pela [Comissão Diretiva Técnica (TSC, sigla em Inglês)][technical steering committee (tsc)] que é responsável pela diretriz de alto nível do projeto.
+
+[consensus seeking]: https://en.wikipedia.org/wiki/Consensus-seeking_decision-making
+[readme.md]: https://github.com/nodejs/node/blob/main/README.md#current-project-team-members
+[tsc]: https://github.com/nodejs/TSC
+[technical steering committee (tsc)]: https://github.com/nodejs/TSC/blob/main/TSC-Charter.md
+[collaborator-guide.md]: https://github.com/nodejs/node/blob/main/doc/contributing/collaborator-guide.md
+[nodejs/node]: https://github.com/nodejs/node
diff --git a/content/about/releases.en.md b/content/about/releases.en.md
new file mode 100644
index 0000000000..e44501dd1e
--- /dev/null
+++ b/content/about/releases.en.md
@@ -0,0 +1,14 @@
+---
+title: releases
+displayTitle: Releases
+description: 'Releases | Node.js'
+authors: ZYSzys, nstanard, mikeal, fhemberger, garybernhardt, piepmatz, boneskull, bjb568
+category: about
+---
+
+Major Node.js versions enter _Current_ release status for six months, which gives library authors time to add support for them.
+After six months, odd-numbered releases (9, 11, etc.) become unsupported, and even-numbered releases (10, 12, etc.) move to _Active LTS_ status and are ready for general use.
+_LTS_ release status is "long-term support", which typically guarantees that critical bugs will be fixed for a total of 30 months.
+Production applications should only use _Active LTS_ or _Maintenance LTS_ releases.
+
+
diff --git a/content/about/releases.fr.md b/content/about/releases.fr.md
new file mode 100644
index 0000000000..7a34ada81f
--- /dev/null
+++ b/content/about/releases.fr.md
@@ -0,0 +1,14 @@
+---
+title: releases
+displayTitle: Sorties
+description: 'Sorties | Node.js'
+authors: ZYSzys, nstanard, mikeal, fhemberger, garybernhardt, piepmatz, boneskull, bjb568, AugustinMauroy
+category: about
+---
+
+Les versions majeures de Node.js passent au statut de version _Current_ pendant six mois, ce qui donne aux auteurs de bibliothèques le temps d'ajouter la prise en charge de ces versions.
+Après six mois, les versions impaires (9, 11, etc.) ne sont plus prises en charge et les versions paires (10, 12, etc.) passent au statut _Active LTS_ et sont prêtes pour une utilisation générale.
+Le statut de la version _LTS_ est un "support à long terme", qui garantit généralement que les bogues critiques seront corrigés pendant un total de 30 mois.
+Il est recommandé aux applications de production d'utiliser que les versions _Active LTS_ ou _Maintenance LTS_.
+
+
diff --git a/content/about/releases.pt.md b/content/about/releases.pt.md
new file mode 100644
index 0000000000..bff9f2da2a
--- /dev/null
+++ b/content/about/releases.pt.md
@@ -0,0 +1,11 @@
+---
+title: releases
+displayTitle: Lançamentos
+description: 'Lançamentos | Node.js'
+authors: ZYSzys, nstanard, mikeal, fhemberger, garybernhardt, piepmatz, boneskull, bjb568, nazarepiedady
+category: about
+---
+
+As versões principais da Node.js entram em estado de lançamento _Atual_ por seis meses, o que dá aos autores de biblioteca tempo para adicionar suporte para elas. Depois de seis meses, os lançamentos numerados com ímpares (9, 11, etc.) tornam-se insuportáveis, e os lançamentos numerados com pares (10, 12, etc) movem-se para o estado _LTS Ativa_ e estão prontas para uso geral. O estado de lançamento _LTS_ é "long-term support" ou "suporte a longo prazo" em Português, o qual garante tipicamente que os bugs críticos serão corrigidos por um total de 30 meses. As aplicações de produção deveriam apenas usar os lançamentos de _LTS Ativa_ ou _LTS de Manutenção_.
+
+
diff --git a/content/about/resources.pt.md b/content/about/resources.pt.md
new file mode 100644
index 0000000000..ba02d4aab6
--- /dev/null
+++ b/content/about/resources.pt.md
@@ -0,0 +1,32 @@
+---
+title: resources
+displayTitle: Recursos
+description: 'Recursos | Node.js'
+authors: XhmikosR, mikeal, fhemberger, Fishrock123, yous, tomgco, tniessen, SMcCandlish, saadq, Trott, Gornstats, piperchester, naoufal, lpinca, j9t, bnoordhuis, harshadsabne, Chris911, MrJithil, nazarepiedady
+category: about
+---
+
+## Descarregamentos do Logótipo
+
+Revise a [política comercial da marca](https://trademark-policy.openjsf.org/) para informações a respeito do uso permissível das marcas e logótipos da Node.js®.
+
+As diretrizes para a exibição visual da marca da Node.js estão descritas nas [Diretrizes Visuais](/static/documents/foundation-visual-guidelines.pdf).
+
+
diff --git a/content/about/security.en.md b/content/about/security.en.md
new file mode 100644
index 0000000000..b1c3ef71be
--- /dev/null
+++ b/content/about/security.en.md
@@ -0,0 +1,73 @@
+---
+title: security
+displayTitle: Security
+description: "Security | Node.js"
+authors: reedloden, XhmikosR, Trott, fhemberger, MaledongGit, yous, sam-github, vdeturckheim, tniessen,richardlau, nschonni, mikeal, e-jigsaw, parthlaw
+category: about
+---
+
+## Reporting a bug in Node.js
+
+Report security bugs in Node.js via [HackerOne](https://hackerone.com/nodejs).
+
+Your report will be acknowledged within 5 days, and you'll receive a more
+detailed response to your report within 10 days indicating the next steps in
+handling your submission.
+
+After the initial reply to your report, the security team will endeavor to keep
+you informed of the progress being made towards a fix and full announcement,
+and may ask for additional information or guidance surrounding the reported
+issue.
+
+### Node.js bug bounty program
+
+The Node.js project engages in an official bug bounty program for security
+researchers and responsible public disclosures. The program is managed through
+the HackerOne platform. See [https://hackerone.com/nodejs](https://hackerone.com/nodejs) for further details.
+
+## Reporting a bug in a third party module
+
+Security bugs in third party modules should be reported to their respective
+maintainers.
+
+## Disclosure policy
+
+Here is the security disclosure policy for Node.js
+
+* The security report is received and is assigned a primary handler. This
+ person will coordinate the fix and release process. The problem is confirmed
+ and a list of all affected versions is determined. Code is audited to find
+ any potential similar problems. Fixes are prepared for all releases which are
+ still under maintenance. These fixes are not committed to the public
+ repository but rather held locally pending the announcement.
+
+* A suggested embargo date for this vulnerability is chosen and a CVE (Common
+ Vulnerabilities and Exposures (CVE®)) is requested for the vulnerability.
+
+* On the embargo date, the Node.js security mailing list is sent a copy of the
+ announcement. The changes are pushed to the public repository and new builds
+ are deployed to nodejs.org. Within 6 hours of the mailing list being
+ notified, a copy of the advisory will be published on the Node.js blog.
+
+* Typically the embargo date will be set 72 hours from the time the CVE is
+ issued. However, this may vary depending on the severity of the bug or
+ difficulty in applying a fix.
+
+* This process can take some time, especially when coordination is required
+ with maintainers of other projects. Every effort will be made to handle the
+ bug in as timely a manner as possible; however, it's important that we follow
+ the release process above to ensure that the disclosure is handled in a
+ consistent manner.
+
+## Receiving security updates
+
+Security notifications will be distributed via the following methods.
+
+* [https://groups.google.com/group/nodejs-sec](https://groups.google.com/group/nodejs-sec)
+* [https://nodejs.org/en/blog/](https://nodejs.org/en/blog/)
+
+## Comments on this policy
+
+If you have suggestions on how this process could be improved please submit a
+[pull request](https://github.com/nodejs/nodejs.org) or
+[file an issue](https://github.com/nodejs/security-wg/issues/new) to discuss.
diff --git a/content/about/security.fr.md b/content/about/security.fr.md
new file mode 100644
index 0000000000..343607f1d6
--- /dev/null
+++ b/content/about/security.fr.md
@@ -0,0 +1,64 @@
+---
+title: security
+displayTitle: "page de sécurité"
+description: "C'est la page de sécurité"
+authors: reedloden, XhmikosR, Trott, fhemberger, MaledongGit, yous, sam-github, vdeturckheim, tniessen,richardlau, nschonni, mikeal, e-jigsaw, parthlaw, AugustinMauroy
+category: Security
+---
+
+## Signaler un bug dans Node.js
+
+Signalez les bogues de sécurité dans Node.js via [HackerOne](https://hackerone.com/nodejs).
+
+Votre rapport fera l'objet d'un accusé de réception dans les 24 heures, et vous recevrez une réponse plus détaillée dans les 48 heures. Réponse plus détaillée à votre rapport dans les 48 heures, indiquant les prochaines étapes de
+traitement de votre demande.
+
+Après la réponse initiale à votre rapport, l'équipe de sécurité s'efforcera de vous tenir
+informé des progrès réalisés en vue d'une correction et d'une annonce complète,
+et pourra vous demander des informations supplémentaires ou des conseils sur le problème signalé.
+problème signalé.
+
+### Programme de primes aux bugs pour Node.js
+
+Le projet Node.js s'engage dans un programme officiel de prime de bogue pour les chercheurs en sécurité et les divulgations publiques responsables.
+responsables. Le programme est géré par
+la plateforme HackerOne. Voir [https://hackerone.com/nodejs](https://hackerone.com/nodejs) pour plus de détails.
+
+## Signaler un bogue dans un module tiers
+
+Les bogues de sécurité dans les modules tiers doivent être signalés à leurs mainteneurs respectifs.
+et doivent être coordonnés par l'équipe de sécurité de l'écosystème Node.js
+Security Team via [HackerOne](https://hackerone.com/nodejs-ecosystem).
+
+Les détails concernant ce processus peuvent être trouvés dans le
+[Dépôt du groupe de travail sur la sécurité](https://github.com/nodejs/security-wg/tree/main/processes/vuln_db.md).
+
+Merci d'améliorer la sécurité de Node.js et de son écosystème. Vos efforts
+et la divulgation responsable sont grandement appréciés et seront reconnus.
+
+## Politique de divulgation
+
+Voici la politique de divulgation de la sécurité pour Node.js
+
+* Le rapport de sécurité est reçu et un gestionnaire principal lui est attribué. Cette personne coordonnera le processus de correction et de publication. Le problème est confirmé et une liste de toutes les versions affectées est déterminée. Le code est audité pour trouver tout problème similaire potentiel. Des correctifs sont préparés pour toutes les versions qui sont encore en maintenance. Ces correctifs ne sont pas engagés dans le dépôt public public mais plutôt conservés localement en attendant l'annonce.
+
+* Une date d'embargo suggérée pour cette vulnérabilité est choisie et un CVE (Common Vulnérabilités et Expositions (CVE®)) est demandé pour cette vulnérabilité.
+
+* À la date d'embargo, la liste de diffusion de la sécurité de Node.js reçoit une copie de l'annonce. annonce. Les changements sont poussés vers le dépôt public et les nouvelles constructions. Sont déployées sur nodejs.org. Dans les 6 heures suivant la notification de la liste de diffusion une copie de l'avis sera publiée sur le blog de Node.js.
+
+* En général, la date d'embargo est fixée à 72 heures à compter de la date de publication du CVE. Cependant, cela peut varier en fonction de la gravité du bogue ou de la difficulté à appliquer un correctif.
+
+* Ce processus peut prendre un certain temps, en particulier lorsqu'une coordination est nécessaire avec les mainteneurs d'autres projets. Avec les mainteneurs d'autres projets. Tous les efforts seront faits pour traiter le bogue de la manière la plus opportune possible ; cependant, il est important que nous suivions le processus de publication ci-dessus afin de garantir que la version finale du logiciel soit disponible. Le processus de publication ci-dessus pour s'assurer que la divulgation est traitée d'une manière cohérente.
+
+## Réception des mises à jour de sécurité
+
+Les notifications de sécurité seront distribuées par les méthodes suivantes.
+
+* [https://groups.google.com/group/nodejs-sec](https://groups.google.com/group/nodejs-sec)
+* [https://nodejs.org/en/blog/](https://nodejs.org/en/blog/)
+
+## Commentaires sur cette politique
+
+Si vous avez des suggestions sur la façon dont ce processus pourrait être amélioré, veuillez soumettre un formulaire de demande d'accès à l'information.
+[pull request](https://github.com/nodejs/nodejs.dev) ou
+[file an issue](https://github.com/nodejs/security-wg/issues/new) pour discuter.
diff --git a/content/about/security.pt.md b/content/about/security.pt.md
new file mode 100644
index 0000000000..be78b222cc
--- /dev/null
+++ b/content/about/security.pt.md
@@ -0,0 +1,48 @@
+---
+title: security
+displayTitle: Segurança
+description: "Segurança | Node.js"
+authors: reedloden, XhmikosR, Trott, fhemberger, MaledongGit, yous, sam-github, vdeturckheim, tniessen,richardlau, nschonni, mikeal, e-jigsaw, parthlaw, nazarepiedady
+category: about
+---
+
+## Reportando um bug na Node.js
+
+Reporte bugs de segurança na Node.js através da [HackerOne](https://hackerone.com/nodejs).
+
+O teu relatório será reconhecido dentro de 5 dias, receberás uma resposta mais detalhada para o teu relatório dentro de 10 dias indicando as próximas etapas na resolução da tua submissão.
+
+Depois da resposta inicial ao teu relatório, a equipa de segurança empenhar-se-á em manter-te informado do progresso sendo feito a uma correção e anúncio completo, e talvez peçam informações adicionais ou orientação envolvendo o problema reportado.
+
+## Programa de recompensa de bug da Node.js
+
+O projeto da Node.js envolve-se em um programa oficial de recompensa de bug para investigadores de segurança e revelações públicas responsáveis. O programa é administrado através da plataforma HackerOne. Consulte [https://hackerone.com/nodejs](https://hackerone.com/nodejs) para mais detalhes.
+
+## Reportando um bug em um módulo de terceiro
+
+Os bugs de segurança em módulos de terceiros devem ser reportados aos seus respetivos responsáveis.
+
+## Política de Revelação
+
+Aqui está a política de revelação de segurança para a Node.js
+
+* O relatório de segurança é recebido e é atribuído um tratador primário. Esta pessoa coordenará o processo de correção e lançamento. O problema é confirmado e a lista de todas as versões afetadas é determinada. O código é passado for auditoria para procurar quaisquer problemas similares. Correções são preparadas para todos os lançamentos que estão sob manutenção. Estas correções não são enviadas para o repositório público mas segurados localmente aguardando o anúncio.
+
+* Uma data de embargo sugerida para esta vulnerabilidade é escolhida e um Vulnerabilidades Comuns e Exposições (CVE®, sigla em Inglês) é registado para a vulnerabilidade.
+
+* Sobre data de embargo, a lista de endereços de segurança da Node.js é enviada uma cópia do anúncio. As mudanças são empurradas para o repositório público e as novas construções são implementadas em produção na [nodejs.org](https://nodejs.org/). Dentro de 6 horas depois da lista de endereços ser notificada, uma cópia do consultivo será publicada no [blogue da Node.js](https://nodejs.org/en/blog/)
+
+* Normalmente a data de embargo será definida 72 horas desde o momento que a CVE for emitida. No entanto, isto pode variar dependendo da severidade do bug ou dificuldade em aplicar uma correção.
+
+* Este processo pode levar algum tempo, especialmente quando a coordenação é exigida por responsáveis de outros projetos. Todo esforço será feito para manusear o bug em tempo oportuno; no entanto, é importante que sigamos o processo de lançamento acima para garantir que a revelação seja resolvida de uma maneira consistente.
+
+## Recebendo atualizações de segurança
+
+As notificações de segurança serão distribuídas através dos seguinte métodos:
+
+* [https://groups.google.com/group/nodejs-sec](https://groups.google.com/group/nodejs-sec)
+* [https://nodejs.org/en/blog/](https://nodejs.org/en/blog/)
+
+## Comentários sobre esta política
+
+Se tiveres sugestões sobre como este processo poderia ser melhorado, submeta um [pedido de atualização do repositório (pull request, em Inglês)](https://github.com/nodejs/nodejs.org) ou [apresentar uma questão](https://github.com/nodejs/security-wg/issues/new) a discutir.
diff --git a/content/api/.gitkeep b/content/api/.gitkeep
new file mode 100644
index 0000000000..f935021a8f
--- /dev/null
+++ b/content/api/.gitkeep
@@ -0,0 +1 @@
+!.gitignore
diff --git a/content/api/v16/addons.en.md b/content/api/v16/addons.en.md
new file mode 100644
index 0000000000..8ae654d6ed
--- /dev/null
+++ b/content/api/v16/addons.en.md
@@ -0,0 +1,1385 @@
+---
+title: 'addons'
+displayTitle: 'C++ addons'
+category: 'api'
+version: 'v16'
+---
+
+
+
+
+
+_Addons_ are dynamically-linked shared objects written in C++. The
+[`require()`][require] function can load addons as ordinary Node.js modules.
+Addons provide an interface between JavaScript and C/C++ libraries.
+
+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 [C/C++ addons with Node-API](n-api.md) for more information on
+Node-API.
+
+When not using Node-API, implementing addons is complicated,
+involving knowledge of several components and APIs:
+
+* [V8][]: the C++ library Node.js uses to provide the
+ JavaScript implementation. V8 provides the mechanisms for creating objects,
+ calling functions, etc. V8's API is documented mostly in the
+ `v8.h` header file (`deps/v8/include/v8.h` in the Node.js source
+ tree), which is also available [online][v8-docs].
+
+* [libuv][]: The C library that implements the Node.js event loop, its worker
+ threads and all of the asynchronous behaviors of the platform. It also
+ serves as a cross-platform abstraction library, giving easy, POSIX-like
+ access across all major operating systems to many common system tasks, such
+ as interacting with the filesystem, sockets, timers, and system events. libuv
+ also provides a 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.
+
+* Internal Node.js libraries. Node.js itself exports C++ APIs that addons can
+ use, the most important of which is the `node::ObjectWrap` class.
+
+* Node.js includes other statically linked libraries including OpenSSL. These
+ other libraries are located in the `deps/` 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
+ [Linking to libraries included with Node.js][] for additional information.
+
+All of the following examples are available for [download][] and may
+be used as the starting-point for an addon.
+
+### Hello world
+
+This "Hello world" example is a simple addon, written in C++, that is the
+equivalent of the following JavaScript code:
+
+```js
+module.exports.hello = () => 'world';
+```
+
+First, create the file `hello.cc`:
+
+```cpp
+// hello.cc
+#include
+
+namespace demo {
+
+using v8::FunctionCallbackInfo;
+using v8::Isolate;
+using v8::Local;
+using v8::Object;
+using v8::String;
+using v8::Value;
+
+void Method(const FunctionCallbackInfo& args) {
+ Isolate* isolate = args.GetIsolate();
+ args.GetReturnValue().Set(String::NewFromUtf8(
+ isolate, "world").ToLocalChecked());
+}
+
+void Initialize(Local exports) {
+ NODE_SET_METHOD(exports, "hello", Method);
+}
+
+NODE_MODULE(NODE_GYP_MODULE_NAME, Initialize)
+
+} // namespace demo
+```
+
+All Node.js addons must export an initialization function following
+the pattern:
+
+```cpp
+void Initialize(Local exports);
+NODE_MODULE(NODE_GYP_MODULE_NAME, Initialize)
+```
+
+There is no semi-colon after `NODE_MODULE` as it's not a function (see
+`node.h`).
+
+The `module_name` must match the filename of the final binary (excluding
+the `.node` suffix).
+
+In the `hello.cc` example, then, the initialization function is `Initialize`
+and the addon module name is `addon`.
+
+When building addons with `node-gyp`, using the macro `NODE_GYP_MODULE_NAME` as
+the first parameter of `NODE_MODULE()` will ensure that the name of the final
+binary will be passed to `NODE_MODULE()`.
+
+#### Context-aware addons
+
+There are environments in which Node.js addons may need to be loaded multiple
+times in multiple contexts. For example, the [Electron][] runtime runs multiple
+instances of Node.js in a single process. Each instance will have its own
+`require()` cache, and thus each instance will need a native addon to behave
+correctly when loaded via `require()`. This means that the addon
+must support multiple initializations.
+
+A context-aware addon can be constructed by using the macro
+`NODE_MODULE_INITIALIZER`, 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:
+
+```cpp
+using namespace v8;
+
+extern "C" NODE_MODULE_EXPORT void
+NODE_MODULE_INITIALIZER(Local exports,
+ Local module,
+ Local context) {
+ /* Perform addon initialization steps here. */
+}
+```
+
+Another option is to use the macro `NODE_MODULE_INIT()`, which will also
+construct a context-aware addon. Unlike `NODE_MODULE()`, which is used to
+construct an addon around a given addon initializer function,
+`NODE_MODULE_INIT()` serves as the declaration of such an initializer to be
+followed by a function body.
+
+The following three variables may be used inside the function body following an
+invocation of `NODE_MODULE_INIT()`:
+
+* `Local exports`,
+* `Local module`, and
+* `Local context`
+
+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.
+
+The context-aware addon can be structured to avoid global static data by
+performing the following steps:
+
+* Define a class which will hold per-addon-instance data and which has a static
+ member of the form
+ ```cpp
+ static void DeleteInstance(void* data) {
+ // Cast `data` to an instance of the class and delete it.
+ }
+ ```
+* Heap-allocate an instance of this class in the addon initializer. This can be
+ accomplished using the `new` keyword.
+* Call `node::AddEnvironmentCleanupHook()`, passing it the above-created
+ instance and a pointer to `DeleteInstance()`. This will ensure the instance is
+ deleted when the environment is torn down.
+* Store the instance of the class in a `v8::External`, and
+* Pass the `v8::External` to all methods exposed to JavaScript by passing it
+ to `v8::FunctionTemplate::New()` or `v8::Function::New()` which creates the
+ native-backed JavaScript functions. The third parameter of
+ `v8::FunctionTemplate::New()` or `v8::Function::New()` accepts the
+ `v8::External` and makes it available in the native callback using the
+ `v8::FunctionCallbackInfo::Data()` method.
+
+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.
+
+The following example illustrates the implementation of a context-aware addon:
+
+```cpp
+#include
+
+using namespace v8;
+
+class AddonData {
+ public:
+ explicit AddonData(Isolate* isolate):
+ call_count(0) {
+ // Ensure this per-addon-instance data is deleted at environment cleanup.
+ node::AddEnvironmentCleanupHook(isolate, DeleteInstance, this);
+ }
+
+ // Per-addon data.
+ int call_count;
+
+ static void DeleteInstance(void* data) {
+ delete static_cast(data);
+ }
+};
+
+static void Method(const v8::FunctionCallbackInfo& info) {
+ // Retrieve the per-addon-instance data.
+ AddonData* data =
+ reinterpret_cast(info.Data().As()->Value());
+ data->call_count++;
+ info.GetReturnValue().Set((double)data->call_count);
+}
+
+// Initialize this addon to be context-aware.
+NODE_MODULE_INIT(/* exports, module, context */) {
+ Isolate* isolate = context->GetIsolate();
+
+ // Create a new instance of `AddonData` for this instance of the addon and
+ // tie its life cycle to that of the Node.js environment.
+ AddonData* data = new AddonData(isolate);
+
+ // Wrap the data in a `v8::External` so we can pass it to the method we
+ // expose.
+ Local external = External::New(isolate, data);
+
+ // Expose the method `Method` to JavaScript, and make sure it receives the
+ // per-addon-instance data we created above by passing `external` as the
+ // third parameter to the `FunctionTemplate` constructor.
+ exports->Set(context,
+ String::NewFromUtf8(isolate, "method").ToLocalChecked(),
+ FunctionTemplate::New(isolate, Method, external)
+ ->GetFunction(context).ToLocalChecked()).FromJust();
+}
+```
+
+##### Worker support
+
+
+
+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:
+
+* Be an Node-API addon, or
+* Be declared as context-aware using `NODE_MODULE_INIT()` as described above
+
+In order to support [`Worker`][] 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 `AddEnvironmentCleanupHook()` function:
+
+```cpp
+void AddEnvironmentCleanupHook(v8::Isolate* isolate,
+ void (*fun)(void* arg),
+ void* arg);
+```
+
+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
+`RemoveEnvironmentCleanupHook()`, which has the same signature. Callbacks are
+run in last-in first-out order.
+
+If necessary, there is an additional pair of `AddEnvironmentCleanupHook()`
+and `RemoveEnvironmentCleanupHook()` 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.
+
+The following `addon.cc` uses `AddEnvironmentCleanupHook`:
+
+```cpp
+// addon.cc
+#include
+#include
+#include
+
+using node::AddEnvironmentCleanupHook;
+using v8::HandleScope;
+using v8::Isolate;
+using v8::Local;
+using v8::Object;
+
+// Note: In a real-world application, do not rely on static/global data.
+static char cookie[] = "yum yum";
+static int cleanup_cb1_called = 0;
+static int cleanup_cb2_called = 0;
+
+static void cleanup_cb1(void* arg) {
+ Isolate* isolate = static_cast(arg);
+ HandleScope scope(isolate);
+ Local obj = Object::New(isolate);
+ assert(!obj.IsEmpty()); // assert VM is still alive
+ assert(obj->IsObject());
+ cleanup_cb1_called++;
+}
+
+static void cleanup_cb2(void* arg) {
+ assert(arg == static_cast(cookie));
+ cleanup_cb2_called++;
+}
+
+static void sanity_check(void*) {
+ assert(cleanup_cb1_called == 1);
+ assert(cleanup_cb2_called == 1);
+}
+
+// Initialize this addon to be context-aware.
+NODE_MODULE_INIT(/* exports, module, context */) {
+ Isolate* isolate = context->GetIsolate();
+
+ AddEnvironmentCleanupHook(isolate, sanity_check, nullptr);
+ AddEnvironmentCleanupHook(isolate, cleanup_cb2, cookie);
+ AddEnvironmentCleanupHook(isolate, cleanup_cb1, isolate);
+}
+```
+
+Test in JavaScript by running:
+
+```js
+// test.js
+require('./build/Release/addon');
+```
+
+#### Building
+
+Once the source code has been written, it must be compiled into the binary
+`addon.node` file. To do so, create a file called `binding.gyp` in the
+top-level of the project describing the build configuration of the module
+using a JSON-like format. This file is used by [node-gyp][], a tool written
+specifically to compile Node.js addons.
+
+```json
+{
+ "targets": [
+ {
+ "target_name": "addon",
+ "sources": [ "hello.cc" ]
+ }
+ ]
+}
+```
+
+A version of the `node-gyp` utility is bundled and distributed with
+Node.js as part of `npm`. This version is not made directly available for
+developers to use and is intended only to support the ability to use the
+`npm install` command to compile and install addons. Developers who wish to
+use `node-gyp` directly can install it using the command
+`npm install -g node-gyp`. See the `node-gyp` [installation instructions][] for
+more information, including platform-specific requirements.
+
+Once the `binding.gyp` file has been created, use `node-gyp configure` to
+generate the appropriate project build files for the current platform. This
+will generate either a `Makefile` (on Unix platforms) or a `vcxproj` file
+(on Windows) in the `build/` directory.
+
+Next, invoke the `node-gyp build` command to generate the compiled `addon.node`
+file. This will be put into the `build/Release/` directory.
+
+When using `npm install` to install a Node.js addon, npm uses its own bundled
+version of `node-gyp` to perform this same set of actions, generating a
+compiled version of the addon for the user's platform on demand.
+
+Once built, the binary addon can be used from within Node.js by pointing
+[`require()`][require] to the built `addon.node` module:
+
+```js
+// hello.js
+const addon = require('./build/Release/addon');
+
+console.log(addon.hello());
+// Prints: 'world'
+```
+
+Because the exact path to the compiled addon binary can vary depending on how
+it is compiled (i.e. sometimes it may be in `./build/Debug/`), addons can use
+the [bindings][] package to load the compiled module.
+
+While the `bindings` package implementation is more sophisticated in how it
+locates addon modules, it is essentially using a `try…catch` pattern similar to:
+
+```js
+try {
+ return require('./build/Release/addon.node');
+} catch (err) {
+ return require('./build/Debug/addon.node');
+}
+```
+
+#### Linking to libraries included with Node.js
+
+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
+`#include <...>` statements (e.g. `#include `) and `node-gyp` will locate
+the appropriate headers automatically. However, there are a few caveats to be
+aware of:
+
+* When `node-gyp` 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.
+
+* `node-gyp` can be run using the `--nodedir` flag pointing at a local Node.js
+ source image. Using this option, the addon will have access to the full set of
+ dependencies.
+
+#### Loading addons using `require()`
+
+The filename extension of the compiled addon binary is `.node` (as opposed
+to `.dll` or `.so`). The [`require()`][require] function is written to look for
+files with the `.node` file extension and initialize those as dynamically-linked
+libraries.
+
+When calling [`require()`][require], the `.node` 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 `addon.js` in the same directory as the binary `addon.node`,
+then [`require('addon')`][require] will give precedence to the `addon.js` file
+and load it instead.
+
+### Native abstractions for Node.js
+
+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.
+
+The [Native Abstractions for Node.js][] (or `nan`) 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 `nan` [examples][] for an
+illustration of how it can be used.
+
+### Node-API
+
+
+
+Stable
+
+
+
+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 [Native Abstractions for Node.js][] APIs, the functions available
+in the Node-API are used.
+
+Creating and maintaining an addon that benefits from the ABI stability
+provided by Node-API carries with it certain
+[implementation considerations][].
+
+To use Node-API in the above "Hello world" example, replace the content of
+`hello.cc` with the following. All other instructions remain the same.
+
+```cpp
+// hello.cc using Node-API
+#include
+
+namespace demo {
+
+napi_value Method(napi_env env, napi_callback_info args) {
+ napi_value greeting;
+ napi_status status;
+
+ status = napi_create_string_utf8(env, "world", NAPI_AUTO_LENGTH, &greeting);
+ if (status != napi_ok) return nullptr;
+ return greeting;
+}
+
+napi_value init(napi_env env, napi_value exports) {
+ napi_status status;
+ napi_value fn;
+
+ status = napi_create_function(env, nullptr, 0, Method, nullptr, &fn);
+ if (status != napi_ok) return nullptr;
+
+ status = napi_set_named_property(env, exports, "hello", fn);
+ if (status != napi_ok) return nullptr;
+ return exports;
+}
+
+NAPI_MODULE(NODE_GYP_MODULE_NAME, init)
+
+} // namespace demo
+```
+
+The functions available and how to use them are documented in
+[C/C++ addons with Node-API](n-api.md).
+
+### Addon examples
+
+Following are some example addons intended to help developers get started. The
+examples use the V8 APIs. Refer to the online [V8 reference][v8-docs]
+for help with the various V8 calls, and V8's [Embedder's Guide][] for an
+explanation of several concepts used such as handles, scopes, function
+templates, etc.
+
+Each of these examples using the following `binding.gyp` file:
+
+```json
+{
+ "targets": [
+ {
+ "target_name": "addon",
+ "sources": [ "addon.cc" ]
+ }
+ ]
+}
+```
+
+In cases where there is more than one `.cc` file, simply add the additional
+filename to the `sources` array:
+
+```json
+"sources": ["addon.cc", "myexample.cc"]
+```
+
+Once the `binding.gyp` file is ready, the example addons can be configured and
+built using `node-gyp`:
+
+```console
+$ node-gyp configure build
+```
+
+#### Function arguments
+
+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.
+
+The following example illustrates how to read function arguments passed from
+JavaScript and how to return a result:
+
+```cpp
+// addon.cc
+#include
+
+namespace demo {
+
+using v8::Exception;
+using v8::FunctionCallbackInfo;
+using v8::Isolate;
+using v8::Local;
+using v8::Number;
+using v8::Object;
+using v8::String;
+using v8::Value;
+
+// This is the implementation of the "add" method
+// Input arguments are passed using the
+// const FunctionCallbackInfo& args struct
+void Add(const FunctionCallbackInfo& args) {
+ Isolate* isolate = args.GetIsolate();
+
+ // Check the number of arguments passed.
+ if (args.Length() < 2) {
+ // Throw an Error that is passed back to JavaScript
+ isolate->ThrowException(Exception::TypeError(
+ String::NewFromUtf8(isolate,
+ "Wrong number of arguments").ToLocalChecked()));
+ return;
+ }
+
+ // Check the argument types
+ if (!args[0]->IsNumber() || !args[1]->IsNumber()) {
+ isolate->ThrowException(Exception::TypeError(
+ String::NewFromUtf8(isolate,
+ "Wrong arguments").ToLocalChecked()));
+ return;
+ }
+
+ // Perform the operation
+ double value =
+ args[0].As()->Value() + args[1].As()->Value();
+ Local num = Number::New(isolate, value);
+
+ // Set the return value (using the passed in
+ // FunctionCallbackInfo&)
+ args.GetReturnValue().Set(num);
+}
+
+void Init(Local exports) {
+ NODE_SET_METHOD(exports, "add", Add);
+}
+
+NODE_MODULE(NODE_GYP_MODULE_NAME, Init)
+
+} // namespace demo
+```
+
+Once compiled, the example addon can be required and used from within Node.js:
+
+```js
+// test.js
+const addon = require('./build/Release/addon');
+
+console.log('This should be eight:', addon.add(3, 5));
+```
+
+#### Callbacks
+
+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:
+
+```cpp
+// addon.cc
+#include
+
+namespace demo {
+
+using v8::Context;
+using v8::Function;
+using v8::FunctionCallbackInfo;
+using v8::Isolate;
+using v8::Local;
+using v8::Null;
+using v8::Object;
+using v8::String;
+using v8::Value;
+
+void RunCallback(const FunctionCallbackInfo& args) {
+ Isolate* isolate = args.GetIsolate();
+ Local context = isolate->GetCurrentContext();
+ Local cb = Local::Cast(args[0]);
+ const unsigned argc = 1;
+ Local argv[argc] = {
+ String::NewFromUtf8(isolate,
+ "hello world").ToLocalChecked() };
+ cb->Call(context, Null(isolate), argc, argv).ToLocalChecked();
+}
+
+void Init(Local exports, Local module) {
+ NODE_SET_METHOD(module, "exports", RunCallback);
+}
+
+NODE_MODULE(NODE_GYP_MODULE_NAME, Init)
+
+} // namespace demo
+```
+
+This example uses a two-argument form of `Init()` that receives the full
+`module` object as the second argument. This allows the addon to completely
+overwrite `exports` with a single function instead of adding the function as a
+property of `exports`.
+
+To test it, run the following JavaScript:
+
+```js
+// test.js
+const addon = require('./build/Release/addon');
+
+addon((msg) => {
+ console.log(msg);
+// Prints: 'hello world'
+});
+```
+
+In this example, the callback function is invoked synchronously.
+
+#### Object factory
+
+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 `msg` that echoes the string passed to `createObject()`:
+
+```cpp
+// addon.cc
+#include
+
+namespace demo {
+
+using v8::Context;
+using v8::FunctionCallbackInfo;
+using v8::Isolate;
+using v8::Local;
+using v8::Object;
+using v8::String;
+using v8::Value;
+
+void CreateObject(const FunctionCallbackInfo& args) {
+ Isolate* isolate = args.GetIsolate();
+ Local context = isolate->GetCurrentContext();
+
+ Local obj = Object::New(isolate);
+ obj->Set(context,
+ String::NewFromUtf8(isolate,
+ "msg").ToLocalChecked(),
+ args[0]->ToString(context).ToLocalChecked())
+ .FromJust();
+
+ args.GetReturnValue().Set(obj);
+}
+
+void Init(Local exports, Local module) {
+ NODE_SET_METHOD(module, "exports", CreateObject);
+}
+
+NODE_MODULE(NODE_GYP_MODULE_NAME, Init)
+
+} // namespace demo
+```
+
+To test it in JavaScript:
+
+```js
+// test.js
+const addon = require('./build/Release/addon');
+
+const obj1 = addon('hello');
+const obj2 = addon('world');
+console.log(obj1.msg, obj2.msg);
+// Prints: 'hello world'
+```
+
+#### Function factory
+
+Another common scenario is creating JavaScript functions that wrap C++
+functions and returning those back to JavaScript:
+
+```cpp
+// addon.cc
+#include
+
+namespace demo {
+
+using v8::Context;
+using v8::Function;
+using v8::FunctionCallbackInfo;
+using v8::FunctionTemplate;
+using v8::Isolate;
+using v8::Local;
+using v8::Object;
+using v8::String;
+using v8::Value;
+
+void MyFunction(const FunctionCallbackInfo& args) {
+ Isolate* isolate = args.GetIsolate();
+ args.GetReturnValue().Set(String::NewFromUtf8(
+ isolate, "hello world").ToLocalChecked());
+}
+
+void CreateFunction(const FunctionCallbackInfo& args) {
+ Isolate* isolate = args.GetIsolate();
+
+ Local context = isolate->GetCurrentContext();
+ Local tpl = FunctionTemplate::New(isolate, MyFunction);
+ Local fn = tpl->GetFunction(context).ToLocalChecked();
+
+ // omit this to make it anonymous
+ fn->SetName(String::NewFromUtf8(
+ isolate, "theFunction").ToLocalChecked());
+
+ args.GetReturnValue().Set(fn);
+}
+
+void Init(Local exports, Local module) {
+ NODE_SET_METHOD(module, "exports", CreateFunction);
+}
+
+NODE_MODULE(NODE_GYP_MODULE_NAME, Init)
+
+} // namespace demo
+```
+
+To test:
+
+```js
+// test.js
+const addon = require('./build/Release/addon');
+
+const fn = addon();
+console.log(fn());
+// Prints: 'hello world'
+```
+
+#### Wrapping C++ objects
+
+It is also possible to wrap C++ objects/classes in a way that allows new
+instances to be created using the JavaScript `new` operator:
+
+```cpp
+// addon.cc
+#include
+#include "myobject.h"
+
+namespace demo {
+
+using v8::Local;
+using v8::Object;
+
+void InitAll(Local exports) {
+ MyObject::Init(exports);
+}
+
+NODE_MODULE(NODE_GYP_MODULE_NAME, InitAll)
+
+} // namespace demo
+```
+
+Then, in `myobject.h`, the wrapper class inherits from `node::ObjectWrap`:
+
+```cpp
+// myobject.h
+#ifndef MYOBJECT_H
+#define MYOBJECT_H
+
+#include
+#include
+
+namespace demo {
+
+class MyObject : public node::ObjectWrap {
+ public:
+ static void Init(v8::Local exports);
+
+ private:
+ explicit MyObject(double value = 0);
+ ~MyObject();
+
+ static void New(const v8::FunctionCallbackInfo& args);
+ static void PlusOne(const v8::FunctionCallbackInfo& args);
+
+ double value_;
+};
+
+} // namespace demo
+
+#endif
+```
+
+In `myobject.cc`, implement the various methods that are to be exposed.
+Below, the method `plusOne()` is exposed by adding it to the constructor's
+prototype:
+
+```cpp
+// myobject.cc
+#include "myobject.h"
+
+namespace demo {
+
+using v8::Context;
+using v8::Function;
+using v8::FunctionCallbackInfo;
+using v8::FunctionTemplate;
+using v8::Isolate;
+using v8::Local;
+using v8::Number;
+using v8::Object;
+using v8::ObjectTemplate;
+using v8::String;
+using v8::Value;
+
+MyObject::MyObject(double value) : value_(value) {
+}
+
+MyObject::~MyObject() {
+}
+
+void MyObject::Init(Local exports) {
+ Isolate* isolate = exports->GetIsolate();
+ Local context = isolate->GetCurrentContext();
+
+ Local addon_data_tpl = ObjectTemplate::New(isolate);
+ addon_data_tpl->SetInternalFieldCount(1); // 1 field for the MyObject::New()
+ Local addon_data =
+ addon_data_tpl->NewInstance(context).ToLocalChecked();
+
+ // Prepare constructor template
+ Local tpl = FunctionTemplate::New(isolate, New, addon_data);
+ tpl->SetClassName(String::NewFromUtf8(isolate, "MyObject").ToLocalChecked());
+ tpl->InstanceTemplate()->SetInternalFieldCount(1);
+
+ // Prototype
+ NODE_SET_PROTOTYPE_METHOD(tpl, "plusOne", PlusOne);
+
+ Local constructor = tpl->GetFunction(context).ToLocalChecked();
+ addon_data->SetInternalField(0, constructor);
+ exports->Set(context, String::NewFromUtf8(
+ isolate, "MyObject").ToLocalChecked(),
+ constructor).FromJust();
+}
+
+void MyObject::New(const FunctionCallbackInfo& args) {
+ Isolate* isolate = args.GetIsolate();
+ Local context = isolate->GetCurrentContext();
+
+ if (args.IsConstructCall()) {
+ // Invoked as constructor: `new MyObject(...)`
+ double value = args[0]->IsUndefined() ?
+ 0 : args[0]->NumberValue(context).FromMaybe(0);
+ MyObject* obj = new MyObject(value);
+ obj->Wrap(args.This());
+ args.GetReturnValue().Set(args.This());
+ } else {
+ // Invoked as plain function `MyObject(...)`, turn into construct call.
+ const int argc = 1;
+ Local argv[argc] = { args[0] };
+ Local cons =
+ args.Data().As()->GetInternalField(0).As();
+ Local result =
+ cons->NewInstance(context, argc, argv).ToLocalChecked();
+ args.GetReturnValue().Set(result);
+ }
+}
+
+void MyObject::PlusOne(const FunctionCallbackInfo& args) {
+ Isolate* isolate = args.GetIsolate();
+
+ MyObject* obj = ObjectWrap::Unwrap(args.Holder());
+ obj->value_ += 1;
+
+ args.GetReturnValue().Set(Number::New(isolate, obj->value_));
+}
+
+} // namespace demo
+```
+
+To build this example, the `myobject.cc` file must be added to the
+`binding.gyp`:
+
+```json
+{
+ "targets": [
+ {
+ "target_name": "addon",
+ "sources": [
+ "addon.cc",
+ "myobject.cc"
+ ]
+ }
+ ]
+}
+```
+
+Test it with:
+
+```js
+// test.js
+const addon = require('./build/Release/addon');
+
+const obj = new addon.MyObject(10);
+console.log(obj.plusOne());
+// Prints: 11
+console.log(obj.plusOne());
+// Prints: 12
+console.log(obj.plusOne());
+// Prints: 13
+```
+
+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.
+
+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.
+
+#### Factory of wrapped objects
+
+Alternatively, it is possible to use a factory pattern to avoid explicitly
+creating object instances using the JavaScript `new` operator:
+
+```js
+const obj = addon.createObject();
+// instead of:
+// const obj = new addon.Object();
+```
+
+First, the `createObject()` method is implemented in `addon.cc`:
+
+```cpp
+// addon.cc
+#include
+#include "myobject.h"
+
+namespace demo {
+
+using v8::FunctionCallbackInfo;
+using v8::Isolate;
+using v8::Local;
+using v8::Object;
+using v8::String;
+using v8::Value;
+
+void CreateObject(const FunctionCallbackInfo& args) {
+ MyObject::NewInstance(args);
+}
+
+void InitAll(Local exports, Local module) {
+ MyObject::Init(exports->GetIsolate());
+
+ NODE_SET_METHOD(module, "exports", CreateObject);
+}
+
+NODE_MODULE(NODE_GYP_MODULE_NAME, InitAll)
+
+} // namespace demo
+```
+
+In `myobject.h`, the static method `NewInstance()` is added to handle
+instantiating the object. This method takes the place of using `new` in
+JavaScript:
+
+```cpp
+// myobject.h
+#ifndef MYOBJECT_H
+#define MYOBJECT_H
+
+#include
+#include
+
+namespace demo {
+
+class MyObject : public node::ObjectWrap {
+ public:
+ static void Init(v8::Isolate* isolate);
+ static void NewInstance(const v8::FunctionCallbackInfo& args);
+
+ private:
+ explicit MyObject(double value = 0);
+ ~MyObject();
+
+ static void New(const v8::FunctionCallbackInfo& args);
+ static void PlusOne(const v8::FunctionCallbackInfo& args);
+ static v8::Global constructor;
+ double value_;
+};
+
+} // namespace demo
+
+#endif
+```
+
+The implementation in `myobject.cc` is similar to the previous example:
+
+```cpp
+// myobject.cc
+#include
+#include "myobject.h"
+
+namespace demo {
+
+using node::AddEnvironmentCleanupHook;
+using v8::Context;
+using v8::Function;
+using v8::FunctionCallbackInfo;
+using v8::FunctionTemplate;
+using v8::Global;
+using v8::Isolate;
+using v8::Local;
+using v8::Number;
+using v8::Object;
+using v8::String;
+using v8::Value;
+
+// Warning! This is not thread-safe, this addon cannot be used for worker
+// threads.
+Global MyObject::constructor;
+
+MyObject::MyObject(double value) : value_(value) {
+}
+
+MyObject::~MyObject() {
+}
+
+void MyObject::Init(Isolate* isolate) {
+ // Prepare constructor template
+ Local tpl = FunctionTemplate::New(isolate, New);
+ tpl->SetClassName(String::NewFromUtf8(isolate, "MyObject").ToLocalChecked());
+ tpl->InstanceTemplate()->SetInternalFieldCount(1);
+
+ // Prototype
+ NODE_SET_PROTOTYPE_METHOD(tpl, "plusOne", PlusOne);
+
+ Local context = isolate->GetCurrentContext();
+ constructor.Reset(isolate, tpl->GetFunction(context).ToLocalChecked());
+
+ AddEnvironmentCleanupHook(isolate, [](void*) {
+ constructor.Reset();
+ }, nullptr);
+}
+
+void MyObject::New(const FunctionCallbackInfo& args) {
+ Isolate* isolate = args.GetIsolate();
+ Local context = isolate->GetCurrentContext();
+
+ if (args.IsConstructCall()) {
+ // Invoked as constructor: `new MyObject(...)`
+ double value = args[0]->IsUndefined() ?
+ 0 : args[0]->NumberValue(context).FromMaybe(0);
+ MyObject* obj = new MyObject(value);
+ obj->Wrap(args.This());
+ args.GetReturnValue().Set(args.This());
+ } else {
+ // Invoked as plain function `MyObject(...)`, turn into construct call.
+ const int argc = 1;
+ Local argv[argc] = { args[0] };
+ Local cons = Local::New(isolate, constructor);
+ Local instance =
+ cons->NewInstance(context, argc, argv).ToLocalChecked();
+ args.GetReturnValue().Set(instance);
+ }
+}
+
+void MyObject::NewInstance(const FunctionCallbackInfo& args) {
+ Isolate* isolate = args.GetIsolate();
+
+ const unsigned argc = 1;
+ Local argv[argc] = { args[0] };
+ Local cons = Local::New(isolate, constructor);
+ Local context = isolate->GetCurrentContext();
+ Local instance =
+ cons->NewInstance(context, argc, argv).ToLocalChecked();
+
+ args.GetReturnValue().Set(instance);
+}
+
+void MyObject::PlusOne(const FunctionCallbackInfo& args) {
+ Isolate* isolate = args.GetIsolate();
+
+ MyObject* obj = ObjectWrap::Unwrap(args.Holder());
+ obj->value_ += 1;
+
+ args.GetReturnValue().Set(Number::New(isolate, obj->value_));
+}
+
+} // namespace demo
+```
+
+Once again, to build this example, the `myobject.cc` file must be added to the
+`binding.gyp`:
+
+```json
+{
+ "targets": [
+ {
+ "target_name": "addon",
+ "sources": [
+ "addon.cc",
+ "myobject.cc"
+ ]
+ }
+ ]
+}
+```
+
+Test it with:
+
+```js
+// test.js
+const createObject = require('./build/Release/addon');
+
+const obj = createObject(10);
+console.log(obj.plusOne());
+// Prints: 11
+console.log(obj.plusOne());
+// Prints: 12
+console.log(obj.plusOne());
+// Prints: 13
+
+const obj2 = createObject(20);
+console.log(obj2.plusOne());
+// Prints: 21
+console.log(obj2.plusOne());
+// Prints: 22
+console.log(obj2.plusOne());
+// Prints: 23
+```
+
+#### Passing wrapped objects around
+
+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
+`node::ObjectWrap::Unwrap`. The following examples shows a function `add()`
+that can take two `MyObject` objects as input arguments:
+
+```cpp
+// addon.cc
+#include
+#include
+#include "myobject.h"
+
+namespace demo {
+
+using v8::Context;
+using v8::FunctionCallbackInfo;
+using v8::Isolate;
+using v8::Local;
+using v8::Number;
+using v8::Object;
+using v8::String;
+using v8::Value;
+
+void CreateObject(const FunctionCallbackInfo& args) {
+ MyObject::NewInstance(args);
+}
+
+void Add(const FunctionCallbackInfo& args) {
+ Isolate* isolate = args.GetIsolate();
+ Local context = isolate->GetCurrentContext();
+
+ MyObject* obj1 = node::ObjectWrap::Unwrap(
+ args[0]->ToObject(context).ToLocalChecked());
+ MyObject* obj2 = node::ObjectWrap::Unwrap(
+ args[1]->ToObject(context).ToLocalChecked());
+
+ double sum = obj1->value() + obj2->value();
+ args.GetReturnValue().Set(Number::New(isolate, sum));
+}
+
+void InitAll(Local exports) {
+ MyObject::Init(exports->GetIsolate());
+
+ NODE_SET_METHOD(exports, "createObject", CreateObject);
+ NODE_SET_METHOD(exports, "add", Add);
+}
+
+NODE_MODULE(NODE_GYP_MODULE_NAME, InitAll)
+
+} // namespace demo
+```
+
+In `myobject.h`, a new public method is added to allow access to private values
+after unwrapping the object.
+
+```cpp
+// myobject.h
+#ifndef MYOBJECT_H
+#define MYOBJECT_H
+
+#include
+#include
+
+namespace demo {
+
+class MyObject : public node::ObjectWrap {
+ public:
+ static void Init(v8::Isolate* isolate);
+ static void NewInstance(const v8::FunctionCallbackInfo& args);
+ inline double value() const { return value_; }
+
+ private:
+ explicit MyObject(double value = 0);
+ ~MyObject();
+
+ static void New(const v8::FunctionCallbackInfo& args);
+ static v8::Global constructor;
+ double value_;
+};
+
+} // namespace demo
+
+#endif
+```
+
+The implementation of `myobject.cc` is similar to before:
+
+```cpp
+// myobject.cc
+#include
+#include "myobject.h"
+
+namespace demo {
+
+using node::AddEnvironmentCleanupHook;
+using v8::Context;
+using v8::Function;
+using v8::FunctionCallbackInfo;
+using v8::FunctionTemplate;
+using v8::Global;
+using v8::Isolate;
+using v8::Local;
+using v8::Object;
+using v8::String;
+using v8::Value;
+
+// Warning! This is not thread-safe, this addon cannot be used for worker
+// threads.
+Global MyObject::constructor;
+
+MyObject::MyObject(double value) : value_(value) {
+}
+
+MyObject::~MyObject() {
+}
+
+void MyObject::Init(Isolate* isolate) {
+ // Prepare constructor template
+ Local tpl = FunctionTemplate::New(isolate, New);
+ tpl->SetClassName(String::NewFromUtf8(isolate, "MyObject").ToLocalChecked());
+ tpl->InstanceTemplate()->SetInternalFieldCount(1);
+
+ Local context = isolate->GetCurrentContext();
+ constructor.Reset(isolate, tpl->GetFunction(context).ToLocalChecked());
+
+ AddEnvironmentCleanupHook(isolate, [](void*) {
+ constructor.Reset();
+ }, nullptr);
+}
+
+void MyObject::New(const FunctionCallbackInfo& args) {
+ Isolate* isolate = args.GetIsolate();
+ Local context = isolate->GetCurrentContext();
+
+ if (args.IsConstructCall()) {
+ // Invoked as constructor: `new MyObject(...)`
+ double value = args[0]->IsUndefined() ?
+ 0 : args[0]->NumberValue(context).FromMaybe(0);
+ MyObject* obj = new MyObject(value);
+ obj->Wrap(args.This());
+ args.GetReturnValue().Set(args.This());
+ } else {
+ // Invoked as plain function `MyObject(...)`, turn into construct call.
+ const int argc = 1;
+ Local argv[argc] = { args[0] };
+ Local cons = Local::New(isolate, constructor);
+ Local instance =
+ cons->NewInstance(context, argc, argv).ToLocalChecked();
+ args.GetReturnValue().Set(instance);
+ }
+}
+
+void MyObject::NewInstance(const FunctionCallbackInfo& args) {
+ Isolate* isolate = args.GetIsolate();
+
+ const unsigned argc = 1;
+ Local argv[argc] = { args[0] };
+ Local cons = Local::New(isolate, constructor);
+ Local context = isolate->GetCurrentContext();
+ Local instance =
+ cons->NewInstance(context, argc, argv).ToLocalChecked();
+
+ args.GetReturnValue().Set(instance);
+}
+
+} // namespace demo
+```
+
+Test it with:
+
+```js
+// test.js
+const addon = require('./build/Release/addon');
+
+const obj1 = addon.createObject(10);
+const obj2 = addon.createObject(20);
+const result = addon.add(obj1, obj2);
+
+console.log(result);
+// Prints: 30
+```
+
+[Electron]: https://electronjs.org/
+[Embedder's Guide]: https://v8.dev/docs/embed
+[Linking to libraries included with Node.js]: #linking-to-libraries-included-with-nodejs
+[Native Abstractions for Node.js]: https://github.com/nodejs/nan
+[V8]: https://v8.dev/
+[`Worker`]: worker_threads.md#class-worker
+[bindings]: https://github.com/TooTallNate/node-bindings
+[download]: https://github.com/nodejs/node-addon-examples
+[examples]: https://github.com/nodejs/nan/tree/HEAD/examples/
+[implementation considerations]: n-api.md#implications-of-abi-stability
+[installation instructions]: https://github.com/nodejs/node-gyp#installation
+[libuv]: https://github.com/libuv/libuv
+[node-gyp]: https://github.com/nodejs/node-gyp
+[require]: /api/v16/modules#requireid
+[v8-docs]: https://v8docs.nodesource.com/
diff --git a/content/api/v16/assert.en.md b/content/api/v16/assert.en.md
new file mode 100644
index 0000000000..30296972d4
--- /dev/null
+++ b/content/api/v16/assert.en.md
@@ -0,0 +1,2212 @@
+---
+title: 'assert'
+displayTitle: 'Assert'
+category: 'api'
+version: 'v16'
+---
+
+
+
+
+
+Stable
+
+
+
+
+
+The `node:assert` module provides a set of assertion functions for verifying
+invariants.
+
+### Strict assertion mode
+
+
+
+In strict assertion mode, non-strict methods behave like their corresponding
+strict methods. For example, [`assert.deepEqual()`][] will behave like
+[`assert.deepStrictEqual()`][].
+
+In strict assertion mode, error messages for objects display a diff. In legacy
+assertion mode, error messages for objects display the objects, often truncated.
+
+To use strict assertion mode:
+
+```mjs|cjs
+import { strict as assert } from 'node:assert';
+--------------
+const assert = require('node:assert').strict;
+```
+
+```mjs|cjs
+import assert from 'node:assert/strict';
+--------------
+const assert = require('node:assert/strict');
+```
+
+Example error diff:
+
+```mjs|cjs
+import { strict as assert } from 'node:assert';
+
+assert.deepEqual([[[1, 2, 3]], 4, 5], [[[1, 2, '3']], 4, 5]);
+// AssertionError: Expected inputs to be strictly deep-equal:
+// + actual - expected ... Lines skipped
+//
+// [
+// [
+// ...
+// 2,
+// + 3
+// - '3'
+// ],
+// ...
+// 5
+// ]
+--------------
+const assert = require('node:assert/strict');
+
+assert.deepEqual([[[1, 2, 3]], 4, 5], [[[1, 2, '3']], 4, 5]);
+// AssertionError: Expected inputs to be strictly deep-equal:
+// + actual - expected ... Lines skipped
+//
+// [
+// [
+// ...
+// 2,
+// + 3
+// - '3'
+// ],
+// ...
+// 5
+// ]
+```
+
+To deactivate the colors, use the `NO_COLOR` or `NODE_DISABLE_COLORS`
+environment variables. This will also deactivate the colors in the REPL. For
+more on color support in terminal environments, read the tty
+[`getColorDepth()`][] documentation.
+
+### Legacy assertion mode
+
+Legacy assertion mode uses the [`==` operator][] in:
+
+* [`assert.deepEqual()`][]
+* [`assert.equal()`][]
+* [`assert.notDeepEqual()`][]
+* [`assert.notEqual()`][]
+
+To use legacy assertion mode:
+
+```mjs|cjs
+import assert from 'node:assert';
+--------------
+const assert = require('node:assert');
+```
+
+Legacy assertion mode may have surprising results, especially when using
+[`assert.deepEqual()`][]:
+
+```cjs
+// WARNING: This does not throw an AssertionError in legacy assertion mode!
+assert.deepEqual(/a/gi, new Date());
+```
+
+### assert.AssertionError
+
+* Extends: [`errors.Error`](/api/v16/errors#error)
+
+Indicates the failure of an assertion. All errors thrown by the `node:assert`
+module will be instances of the `AssertionError` class.
+
+#### `new assert.AssertionError(options)`
+
+
+
+* `options` [`Object`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object)
+ * `message` [`string`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type) If provided, the error message is set to this value.
+ * `actual` [`any`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Data_types) The `actual` property on the error instance.
+ * `expected` [`any`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Data_types) The `expected` property on the error instance.
+ * `operator` [`string`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type) The `operator` property on the error instance.
+ * `stackStartFn` [`Function`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Function) If provided, the generated stack trace omits
+ frames before this function.
+
+A subclass of `Error` that indicates the failure of an assertion.
+
+All instances contain the built-in `Error` properties (`message` and `name`)
+and:
+
+* `actual` [`any`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Data_types) Set to the `actual` argument for methods such as
+ [`assert.strictEqual()`][].
+* `expected` [`any`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Data_types) Set to the `expected` value for methods such as
+ [`assert.strictEqual()`][].
+* `generatedMessage` [`boolean`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Boolean_type) Indicates if the message was auto-generated
+ (`true`) or not.
+* `code` [`string`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type) Value is always `ERR_ASSERTION` to show that the error is an
+ assertion error.
+* `operator` [`string`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type) Set to the passed in operator value.
+
+```mjs|cjs
+import assert from 'node:assert';
+
+// Generate an AssertionError to compare the error message later:
+const { message } = new assert.AssertionError({
+ actual: 1,
+ expected: 2,
+ operator: 'strictEqual'
+});
+
+// Verify error output:
+try {
+ assert.strictEqual(1, 2);
+} catch (err) {
+ assert(err instanceof assert.AssertionError);
+ assert.strictEqual(err.message, message);
+ assert.strictEqual(err.name, 'AssertionError');
+ assert.strictEqual(err.actual, 1);
+ assert.strictEqual(err.expected, 2);
+ assert.strictEqual(err.code, 'ERR_ASSERTION');
+ assert.strictEqual(err.operator, 'strictEqual');
+ assert.strictEqual(err.generatedMessage, true);
+}
+--------------
+const assert = require('node:assert');
+
+// Generate an AssertionError to compare the error message later:
+const { message } = new assert.AssertionError({
+ actual: 1,
+ expected: 2,
+ operator: 'strictEqual'
+});
+
+// Verify error output:
+try {
+ assert.strictEqual(1, 2);
+} catch (err) {
+ assert(err instanceof assert.AssertionError);
+ assert.strictEqual(err.message, message);
+ assert.strictEqual(err.name, 'AssertionError');
+ assert.strictEqual(err.actual, 1);
+ assert.strictEqual(err.expected, 2);
+ assert.strictEqual(err.code, 'ERR_ASSERTION');
+ assert.strictEqual(err.operator, 'strictEqual');
+ assert.strictEqual(err.generatedMessage, true);
+}
+```
+
+### `assert.CallTracker`
+
+
+
+
+
+Experimental
+
+
+
+This feature is currently experimental and behavior might still change.
+
+#### `new assert.CallTracker()`
+
+
+
+Creates a new [`CallTracker`][] object which can be used to track if functions
+were called a specific number of times. The `tracker.verify()` must be called
+for the verification to take place. The usual pattern would be to call it in a
+[`process.on('exit')`][] handler.
+
+```mjs|cjs
+import assert from 'node:assert';
+import process from 'node:process';
+
+const tracker = new assert.CallTracker();
+
+function func() {}
+
+// callsfunc() must be called exactly 1 time before tracker.verify().
+const callsfunc = tracker.calls(func, 1);
+
+callsfunc();
+
+// Calls tracker.verify() and verifies if all tracker.calls() functions have
+// been called exact times.
+process.on('exit', () => {
+ tracker.verify();
+});
+--------------
+const assert = require('node:assert');
+
+const tracker = new assert.CallTracker();
+
+function func() {}
+
+// callsfunc() must be called exactly 1 time before tracker.verify().
+const callsfunc = tracker.calls(func, 1);
+
+callsfunc();
+
+// Calls tracker.verify() and verifies if all tracker.calls() functions have
+// been called exact times.
+process.on('exit', () => {
+ tracker.verify();
+});
+```
+
+#### `tracker.calls([fn][, exact])`
+
+
+
+* `fn` [`Function`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Function) **Default:** A no-op function.
+* `exact` [`number`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type) **Default:** `1`.
+* Returns: [`Function`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Function) that wraps `fn`.
+
+The wrapper function is expected to be called exactly `exact` times. If the
+function has not been called exactly `exact` times when
+[`tracker.verify()`][] is called, then [`tracker.verify()`][] will throw an
+error.
+
+```mjs|cjs
+import assert from 'node:assert';
+
+// Creates call tracker.
+const tracker = new assert.CallTracker();
+
+function func() {}
+
+// Returns a function that wraps func() that must be called exact times
+// before tracker.verify().
+const callsfunc = tracker.calls(func);
+--------------
+const assert = require('node:assert');
+
+// Creates call tracker.
+const tracker = new assert.CallTracker();
+
+function func() {}
+
+// Returns a function that wraps func() that must be called exact times
+// before tracker.verify().
+const callsfunc = tracker.calls(func);
+```
+
+#### `tracker.getCalls(fn)`
+
+
+
+* `fn` [`Function`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Function).
+
+* Returns: [`Array`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array) with all the calls to a tracked function.
+
+* Object [`Object`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object)
+ * `thisArg` [`Object`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object)
+ * `arguments` [`Array`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array) the arguments passed to the tracked function
+
+```mjs|cjs
+import assert from 'node:assert';
+
+const tracker = new assert.CallTracker();
+
+function func() {}
+const callsfunc = tracker.calls(func);
+callsfunc(1, 2, 3);
+
+assert.deepStrictEqual(tracker.getCalls(callsfunc),
+ [{ thisArg: this, arguments: [1, 2, 3 ] }]);
+--------------
+const assert = require('node:assert');
+
+// Creates call tracker.
+const tracker = new assert.CallTracker();
+
+function func() {}
+const callsfunc = tracker.calls(func);
+callsfunc(1, 2, 3);
+
+assert.deepStrictEqual(tracker.getCalls(callsfunc),
+ [{ thisArg: this, arguments: [1, 2, 3 ] }]);
+```
+
+#### `tracker.report()`
+
+
+
+* Returns: [`Array`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array) of objects containing information about the wrapper functions
+ returned by [`tracker.calls()`][].
+* Object [`Object`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object)
+ * `message` [`string`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type)
+ * `actual` [`number`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type) The actual number of times the function was called.
+ * `expected` [`number`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type) The number of times the function was expected to be
+ called.
+ * `operator` [`string`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type) The name of the function that is wrapped.
+ * `stack` [`Object`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object) A stack trace of the function.
+
+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.
+
+```mjs|cjs
+import assert from 'node:assert';
+
+// Creates call tracker.
+const tracker = new assert.CallTracker();
+
+function func() {}
+
+// Returns a function that wraps func() that must be called exact times
+// before tracker.verify().
+const callsfunc = tracker.calls(func, 2);
+
+// Returns an array containing information on callsfunc()
+tracker.report();
+// [
+// {
+// message: 'Expected the func function to be executed 2 time(s) but was
+// executed 0 time(s).',
+// actual: 0,
+// expected: 2,
+// operator: 'func',
+// stack: stack trace
+// }
+// ]
+--------------
+const assert = require('node:assert');
+
+// Creates call tracker.
+const tracker = new assert.CallTracker();
+
+function func() {}
+
+// Returns a function that wraps func() that must be called exact times
+// before tracker.verify().
+const callsfunc = tracker.calls(func, 2);
+
+// Returns an array containing information on callsfunc()
+tracker.report();
+// [
+// {
+// message: 'Expected the func function to be executed 2 time(s) but was
+// executed 0 time(s).',
+// actual: 0,
+// expected: 2,
+// operator: 'func',
+// stack: stack trace
+// }
+// ]
+```
+
+#### `tracker.reset([fn])`
+
+
+
+* `fn` [`Function`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Function) a tracked function to reset.
+
+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
+
+```mjs|cjs
+import assert from 'node:assert';
+
+const tracker = new assert.CallTracker();
+
+function func() {}
+const callsfunc = tracker.calls(func);
+
+callsfunc();
+// Tracker was called once
+tracker.getCalls(callsfunc).length === 1;
+
+tracker.reset(callsfunc);
+tracker.getCalls(callsfunc).length === 0;
+--------------
+const assert = require('node:assert');
+
+function func() {}
+const callsfunc = tracker.calls(func);
+
+callsfunc();
+// Tracker was called once
+tracker.getCalls(callsfunc).length === 1;
+
+tracker.reset(callsfunc);
+tracker.getCalls(callsfunc).length === 0;
+```
+
+#### `tracker.verify()`
+
+
+
+Iterates through the list of functions passed to
+[`tracker.calls()`][] and will throw an error for functions that
+have not been called the expected number of times.
+
+```mjs|cjs
+import assert from 'node:assert';
+
+// Creates call tracker.
+const tracker = new assert.CallTracker();
+
+function func() {}
+
+// Returns a function that wraps func() that must be called exact times
+// before tracker.verify().
+const callsfunc = tracker.calls(func, 2);
+
+callsfunc();
+
+// Will throw an error since callsfunc() was only called once.
+tracker.verify();
+--------------
+const assert = require('node:assert');
+
+// Creates call tracker.
+const tracker = new assert.CallTracker();
+
+function func() {}
+
+// Returns a function that wraps func() that must be called exact times
+// before tracker.verify().
+const callsfunc = tracker.calls(func, 2);
+
+callsfunc();
+
+// Will throw an error since callsfunc() was only called once.
+tracker.verify();
+```
+
+### `assert(value[, message])`
+
+
+
+* `value` [`any`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Data_types) The input that is checked for being truthy.
+* `message` [`string`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type) | [`Error`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Error)
+
+An alias of [`assert.ok()`][].
+
+### `assert.deepEqual(actual, expected[, message])`
+
+
+
+* `actual` [`any`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Data_types)
+* `expected` [`any`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Data_types)
+* `message` [`string`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type) | [`Error`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Error)
+
+**Strict assertion mode**
+
+An alias of [`assert.deepStrictEqual()`][].
+
+**Legacy assertion mode**
+
+
+
+Legacy: Use [`assert.deepStrictEqual()`][] instead.
+
+
+
+Tests for deep equality between the `actual` and `expected` parameters. Consider
+using [`assert.deepStrictEqual()`][] instead. [`assert.deepEqual()`][] can have
+surprising results.
+
+_Deep equality_ means that the enumerable "own" properties of child objects
+are also recursively evaluated by the following rules.
+
+#### Comparison details
+
+* Primitive values are compared with the [`==` operator][],
+ with the exception of `NaN`. It is treated as being identical in case
+ both sides are `NaN`.
+* [Type tags][Object.prototype.toString()] of objects should be the same.
+* Only [enumerable "own" properties][] are considered.
+* [`Error`][] names and messages are always compared, even if these are not
+ enumerable properties.
+* [Object wrappers][] are compared both as objects and unwrapped values.
+* `Object` properties are compared unordered.
+* [`Map`][] keys and [`Set`][] items are compared unordered.
+* Recursion stops when both sides differ or both sides encounter a circular
+ reference.
+* Implementation does not test the [`[[Prototype]]`][prototype-spec] of
+ objects.
+* [`Symbol`][] properties are not compared.
+* [`WeakMap`][] and [`WeakSet`][] comparison does not rely on their values.
+
+The following example does not throw an [`AssertionError`][] because the
+primitives are compared using the [`==` operator][].
+
+```mjs|cjs
+import assert from 'node:assert';
+// WARNING: This does not throw an AssertionError!
+
+assert.deepEqual('+00000000', false);
+--------------
+const assert = require('node:assert');
+// WARNING: This does not throw an AssertionError!
+
+assert.deepEqual('+00000000', false);
+```
+
+"Deep" equality means that the enumerable "own" properties of child objects
+are evaluated also:
+
+```mjs|cjs
+import assert from 'node:assert';
+
+const obj1 = {
+ a: {
+ b: 1
+ }
+};
+const obj2 = {
+ a: {
+ b: 2
+ }
+};
+const obj3 = {
+ a: {
+ b: 1
+ }
+};
+const obj4 = Object.create(obj1);
+
+assert.deepEqual(obj1, obj1);
+// OK
+
+// Values of b are different:
+assert.deepEqual(obj1, obj2);
+// AssertionError: { a: { b: 1 } } deepEqual { a: { b: 2 } }
+
+assert.deepEqual(obj1, obj3);
+// OK
+
+// Prototypes are ignored:
+assert.deepEqual(obj1, obj4);
+// AssertionError: { a: { b: 1 } } deepEqual {}
+--------------
+const assert = require('node:assert');
+
+const obj1 = {
+ a: {
+ b: 1
+ }
+};
+const obj2 = {
+ a: {
+ b: 2
+ }
+};
+const obj3 = {
+ a: {
+ b: 1
+ }
+};
+const obj4 = Object.create(obj1);
+
+assert.deepEqual(obj1, obj1);
+// OK
+
+// Values of b are different:
+assert.deepEqual(obj1, obj2);
+// AssertionError: { a: { b: 1 } } deepEqual { a: { b: 2 } }
+
+assert.deepEqual(obj1, obj3);
+// OK
+
+// Prototypes are ignored:
+assert.deepEqual(obj1, obj4);
+// AssertionError: { a: { b: 1 } } deepEqual {}
+```
+
+If the values are not equal, an [`AssertionError`][] is thrown with a `message`
+property set equal to the value of the `message` parameter. If the `message`
+parameter is undefined, a default error message is assigned. If the `message`
+parameter is an instance of an [`Error`][] then it will be thrown instead of the
+[`AssertionError`][].
+
+### `assert.deepStrictEqual(actual, expected[, message])`
+
+
+
+* `actual` [`any`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Data_types)
+* `expected` [`any`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Data_types)
+* `message` [`string`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type) | [`Error`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Error)
+
+Tests for deep equality between the `actual` and `expected` parameters.
+"Deep" equality means that the enumerable "own" properties of child objects
+are recursively evaluated also by the following rules.
+
+#### Comparison details
+
+* Primitive values are compared using [`Object.is()`][].
+* [Type tags][Object.prototype.toString()] of objects should be the same.
+* [`[[Prototype]]`][prototype-spec] of objects are compared using
+ the [`===` operator][].
+* Only [enumerable "own" properties][] are considered.
+* [`Error`][] names and messages are always compared, even if these are not
+ enumerable properties.
+* Enumerable own [`Symbol`][] properties are compared as well.
+* [Object wrappers][] are compared both as objects and unwrapped values.
+* `Object` properties are compared unordered.
+* [`Map`][] keys and [`Set`][] items are compared unordered.
+* Recursion stops when both sides differ or both sides encounter a circular
+ reference.
+* [`WeakMap`][] and [`WeakSet`][] comparison does not rely on their values. See
+ below for further details.
+
+```mjs|cjs
+import assert from 'node:assert/strict';
+
+// This fails because 1 !== '1'.
+assert.deepStrictEqual({ a: 1 }, { a: '1' });
+// AssertionError: Expected inputs to be strictly deep-equal:
+// + actual - expected
+//
+// {
+// + a: 1
+// - a: '1'
+// }
+
+// The following objects don't have own properties
+const date = new Date();
+const object = {};
+const fakeDate = {};
+Object.setPrototypeOf(fakeDate, Date.prototype);
+
+// Different [[Prototype]]:
+assert.deepStrictEqual(object, fakeDate);
+// AssertionError: Expected inputs to be strictly deep-equal:
+// + actual - expected
+//
+// + {}
+// - Date {}
+
+// Different type tags:
+assert.deepStrictEqual(date, fakeDate);
+// AssertionError: Expected inputs to be strictly deep-equal:
+// + actual - expected
+//
+// + 2018-04-26T00:49:08.604Z
+// - Date {}
+
+assert.deepStrictEqual(NaN, NaN);
+// OK because Object.is(NaN, NaN) is true.
+
+// Different unwrapped numbers:
+assert.deepStrictEqual(new Number(1), new Number(2));
+// AssertionError: Expected inputs to be strictly deep-equal:
+// + actual - expected
+//
+// + [Number: 1]
+// - [Number: 2]
+
+assert.deepStrictEqual(new String('foo'), Object('foo'));
+// OK because the object and the string are identical when unwrapped.
+
+assert.deepStrictEqual(-0, -0);
+// OK
+
+// Different zeros:
+assert.deepStrictEqual(0, -0);
+// AssertionError: Expected inputs to be strictly deep-equal:
+// + actual - expected
+//
+// + 0
+// - -0
+
+const symbol1 = Symbol();
+const symbol2 = Symbol();
+assert.deepStrictEqual({ [symbol1]: 1 }, { [symbol1]: 1 });
+// OK, because it is the same symbol on both objects.
+
+assert.deepStrictEqual({ [symbol1]: 1 }, { [symbol2]: 1 });
+// AssertionError [ERR_ASSERTION]: Inputs identical but not reference equal:
+//
+// {
+// [Symbol()]: 1
+// }
+
+const weakMap1 = new WeakMap();
+const weakMap2 = new WeakMap([[{}, {}]]);
+const weakMap3 = new WeakMap();
+weakMap3.unequal = true;
+
+assert.deepStrictEqual(weakMap1, weakMap2);
+// OK, because it is impossible to compare the entries
+
+// Fails because weakMap3 has a property that weakMap1 does not contain:
+assert.deepStrictEqual(weakMap1, weakMap3);
+// AssertionError: Expected inputs to be strictly deep-equal:
+// + actual - expected
+//
+// WeakMap {
+// + [items unknown]
+// - [items unknown],
+// - unequal: true
+// }
+--------------
+const assert = require('node:assert/strict');
+
+// This fails because 1 !== '1'.
+assert.deepStrictEqual({ a: 1 }, { a: '1' });
+// AssertionError: Expected inputs to be strictly deep-equal:
+// + actual - expected
+//
+// {
+// + a: 1
+// - a: '1'
+// }
+
+// The following objects don't have own properties
+const date = new Date();
+const object = {};
+const fakeDate = {};
+Object.setPrototypeOf(fakeDate, Date.prototype);
+
+// Different [[Prototype]]:
+assert.deepStrictEqual(object, fakeDate);
+// AssertionError: Expected inputs to be strictly deep-equal:
+// + actual - expected
+//
+// + {}
+// - Date {}
+
+// Different type tags:
+assert.deepStrictEqual(date, fakeDate);
+// AssertionError: Expected inputs to be strictly deep-equal:
+// + actual - expected
+//
+// + 2018-04-26T00:49:08.604Z
+// - Date {}
+
+assert.deepStrictEqual(NaN, NaN);
+// OK because Object.is(NaN, NaN) is true.
+
+// Different unwrapped numbers:
+assert.deepStrictEqual(new Number(1), new Number(2));
+// AssertionError: Expected inputs to be strictly deep-equal:
+// + actual - expected
+//
+// + [Number: 1]
+// - [Number: 2]
+
+assert.deepStrictEqual(new String('foo'), Object('foo'));
+// OK because the object and the string are identical when unwrapped.
+
+assert.deepStrictEqual(-0, -0);
+// OK
+
+// Different zeros:
+assert.deepStrictEqual(0, -0);
+// AssertionError: Expected inputs to be strictly deep-equal:
+// + actual - expected
+//
+// + 0
+// - -0
+
+const symbol1 = Symbol();
+const symbol2 = Symbol();
+assert.deepStrictEqual({ [symbol1]: 1 }, { [symbol1]: 1 });
+// OK, because it is the same symbol on both objects.
+
+assert.deepStrictEqual({ [symbol1]: 1 }, { [symbol2]: 1 });
+// AssertionError [ERR_ASSERTION]: Inputs identical but not reference equal:
+//
+// {
+// [Symbol()]: 1
+// }
+
+const weakMap1 = new WeakMap();
+const weakMap2 = new WeakMap([[{}, {}]]);
+const weakMap3 = new WeakMap();
+weakMap3.unequal = true;
+
+assert.deepStrictEqual(weakMap1, weakMap2);
+// OK, because it is impossible to compare the entries
+
+// Fails because weakMap3 has a property that weakMap1 does not contain:
+assert.deepStrictEqual(weakMap1, weakMap3);
+// AssertionError: Expected inputs to be strictly deep-equal:
+// + actual - expected
+//
+// WeakMap {
+// + [items unknown]
+// - [items unknown],
+// - unequal: true
+// }
+```
+
+If the values are not equal, an [`AssertionError`][] is thrown with a `message`
+property set equal to the value of the `message` parameter. If the `message`
+parameter is undefined, a default error message is assigned. If the `message`
+parameter is an instance of an [`Error`][] then it will be thrown instead of the
+`AssertionError`.
+
+### `assert.doesNotMatch(string, regexp[, message])`
+
+
+
+* `string` [`string`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type)
+* `regexp` [`RegExp`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/RegExp)
+* `message` [`string`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type) | [`Error`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Error)
+
+Expects the `string` input not to match the regular expression.
+
+```mjs|cjs
+import assert from 'node:assert/strict';
+
+assert.doesNotMatch('I will fail', /fail/);
+// AssertionError [ERR_ASSERTION]: The input was expected to not match the ...
+
+assert.doesNotMatch(123, /pass/);
+// AssertionError [ERR_ASSERTION]: The "string" argument must be of type string.
+
+assert.doesNotMatch('I will pass', /different/);
+// OK
+--------------
+const assert = require('node:assert/strict');
+
+assert.doesNotMatch('I will fail', /fail/);
+// AssertionError [ERR_ASSERTION]: The input was expected to not match the ...
+
+assert.doesNotMatch(123, /pass/);
+// AssertionError [ERR_ASSERTION]: The "string" argument must be of type string.
+
+assert.doesNotMatch('I will pass', /different/);
+// OK
+```
+
+If the values do match, or if the `string` argument is of another type than
+`string`, an [`AssertionError`][] is thrown with a `message` property set equal
+to the value of the `message` parameter. If the `message` parameter is
+undefined, a default error message is assigned. If the `message` parameter is an
+instance of an [`Error`][] then it will be thrown instead of the
+[`AssertionError`][].
+
+### `assert.doesNotReject(asyncFn[, error][, message])`
+
+
+
+* `asyncFn` [`Function`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Function) | [`Promise`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Promise)
+* `error` [`RegExp`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/RegExp) | [`Function`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Function)
+* `message` [`string`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type)
+
+Awaits the `asyncFn` promise or, if `asyncFn` is a function, immediately
+calls the function and awaits the returned promise to complete. It will then
+check that the promise is not rejected.
+
+If `asyncFn` is a function and it throws an error synchronously,
+`assert.doesNotReject()` will return a rejected `Promise` with that error. If
+the function does not return a promise, `assert.doesNotReject()` will return a
+rejected `Promise` with an [`ERR_INVALID_RETURN_VALUE`][] error. In both cases
+the error handler is skipped.
+
+Using `assert.doesNotReject()` 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.
+
+If specified, `error` can be a [`Class`][], [`RegExp`][], or a validation
+function. See [`assert.throws()`][] for more details.
+
+Besides the async nature to await the completion behaves identically to
+[`assert.doesNotThrow()`][].
+
+```mjs|cjs
+import assert from 'node:assert/strict';
+
+await assert.doesNotReject(
+ async () => {
+ throw new TypeError('Wrong value');
+ },
+ SyntaxError
+);
+--------------
+const assert = require('node:assert/strict');
+
+(async () => {
+ await assert.doesNotReject(
+ async () => {
+ throw new TypeError('Wrong value');
+ },
+ SyntaxError
+ );
+})();
+```
+
+```mjs|cjs
+import assert from 'node:assert/strict';
+
+assert.doesNotReject(Promise.reject(new TypeError('Wrong value')))
+ .then(() => {
+ // ...
+ });
+--------------
+const assert = require('node:assert/strict');
+
+assert.doesNotReject(Promise.reject(new TypeError('Wrong value')))
+ .then(() => {
+ // ...
+ });
+```
+
+### `assert.doesNotThrow(fn[, error][, message])`
+
+
+
+* `fn` [`Function`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Function)
+* `error` [`RegExp`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/RegExp) | [`Function`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Function)
+* `message` [`string`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type)
+
+Asserts that the function `fn` does not throw an error.
+
+Using `assert.doesNotThrow()` 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.
+
+When `assert.doesNotThrow()` is called, it will immediately call the `fn`
+function.
+
+If an error is thrown and it is the same type as that specified by the `error`
+parameter, then an [`AssertionError`][] is thrown. If the error is of a
+different type, or if the `error` parameter is undefined, the error is
+propagated back to the caller.
+
+If specified, `error` can be a [`Class`][], [`RegExp`][], or a validation
+function. See [`assert.throws()`][] for more details.
+
+The following, for instance, will throw the [`TypeError`][] because there is no
+matching error type in the assertion:
+
+```mjs|cjs
+import assert from 'node:assert/strict';
+
+assert.doesNotThrow(
+ () => {
+ throw new TypeError('Wrong value');
+ },
+ SyntaxError
+);
+--------------
+const assert = require('node:assert/strict');
+
+assert.doesNotThrow(
+ () => {
+ throw new TypeError('Wrong value');
+ },
+ SyntaxError
+);
+```
+
+However, the following will result in an [`AssertionError`][] with the message
+'Got unwanted exception...':
+
+```mjs|cjs
+import assert from 'node:assert/strict';
+
+assert.doesNotThrow(
+ () => {
+ throw new TypeError('Wrong value');
+ },
+ TypeError
+);
+--------------
+const assert = require('node:assert/strict');
+
+assert.doesNotThrow(
+ () => {
+ throw new TypeError('Wrong value');
+ },
+ TypeError
+);
+```
+
+If an [`AssertionError`][] is thrown and a value is provided for the `message`
+parameter, the value of `message` will be appended to the [`AssertionError`][]
+message:
+
+```mjs|cjs
+import assert from 'node:assert/strict';
+
+assert.doesNotThrow(
+ () => {
+ throw new TypeError('Wrong value');
+ },
+ /Wrong value/,
+ 'Whoops'
+);
+// Throws: AssertionError: Got unwanted exception: Whoops
+--------------
+const assert = require('node:assert/strict');
+
+assert.doesNotThrow(
+ () => {
+ throw new TypeError('Wrong value');
+ },
+ /Wrong value/,
+ 'Whoops'
+);
+// Throws: AssertionError: Got unwanted exception: Whoops
+```
+
+### `assert.equal(actual, expected[, message])`
+
+
+
+* `actual` [`any`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Data_types)
+* `expected` [`any`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Data_types)
+* `message` [`string`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type) | [`Error`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Error)
+
+**Strict assertion mode**
+
+An alias of [`assert.strictEqual()`][].
+
+**Legacy assertion mode**
+
+
+
+Legacy: Use [`assert.strictEqual()`][] instead.
+
+
+
+Tests shallow, coercive equality between the `actual` and `expected` parameters
+using the [`==` operator][]. `NaN` is specially handled
+and treated as being identical if both sides are `NaN`.
+
+```mjs|cjs
+import assert from 'node:assert';
+
+assert.equal(1, 1);
+// OK, 1 == 1
+assert.equal(1, '1');
+// OK, 1 == '1'
+assert.equal(NaN, NaN);
+// OK
+
+assert.equal(1, 2);
+// AssertionError: 1 == 2
+assert.equal({ a: { b: 1 } }, { a: { b: 1 } });
+// AssertionError: { a: { b: 1 } } == { a: { b: 1 } }
+--------------
+const assert = require('node:assert');
+
+assert.equal(1, 1);
+// OK, 1 == 1
+assert.equal(1, '1');
+// OK, 1 == '1'
+assert.equal(NaN, NaN);
+// OK
+
+assert.equal(1, 2);
+// AssertionError: 1 == 2
+assert.equal({ a: { b: 1 } }, { a: { b: 1 } });
+// AssertionError: { a: { b: 1 } } == { a: { b: 1 } }
+```
+
+If the values are not equal, an [`AssertionError`][] is thrown with a `message`
+property set equal to the value of the `message` parameter. If the `message`
+parameter is undefined, a default error message is assigned. If the `message`
+parameter is an instance of an [`Error`][] then it will be thrown instead of the
+`AssertionError`.
+
+### `assert.fail([message])`
+
+
+
+* `message` [`string`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type) | [`Error`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Error) **Default:** `'Failed'`
+
+Throws an [`AssertionError`][] with the provided error message or a default
+error message. If the `message` parameter is an instance of an [`Error`][] then
+it will be thrown instead of the [`AssertionError`][].
+
+```mjs|cjs
+import assert from 'node:assert/strict';
+
+assert.fail();
+// AssertionError [ERR_ASSERTION]: Failed
+
+assert.fail('boom');
+// AssertionError [ERR_ASSERTION]: boom
+
+assert.fail(new TypeError('need array'));
+// TypeError: need array
+--------------
+const assert = require('node:assert/strict');
+
+assert.fail();
+// AssertionError [ERR_ASSERTION]: Failed
+
+assert.fail('boom');
+// AssertionError [ERR_ASSERTION]: boom
+
+assert.fail(new TypeError('need array'));
+// TypeError: need array
+```
+
+Using `assert.fail()` with more than two arguments is possible but deprecated.
+See below for further details.
+
+### `assert.fail(actual, expected[, message[, operator[, stackStartFn]]])`
+
+
+
+
+
+Deprecated: Use `assert.fail([message])` or other assert functions instead.
+
+
+
+* `actual` [`any`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Data_types)
+* `expected` [`any`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Data_types)
+* `message` [`string`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type) | [`Error`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Error)
+* `operator` [`string`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type) **Default:** `'!='`
+* `stackStartFn` [`Function`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Function) **Default:** `assert.fail`
+
+If `message` is falsy, the error message is set as the values of `actual` and
+`expected` separated by the provided `operator`. If just the two `actual` and
+`expected` arguments are provided, `operator` will default to `'!='`. If
+`message` 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
+`stackStartFn` is provided, all stack frames above that function will be
+removed from stacktrace (see [`Error.captureStackTrace`][]). If no arguments are
+given, the default message `Failed` will be used.
+
+```mjs|cjs
+import assert from 'node:assert/strict';
+
+assert.fail('a', 'b');
+// AssertionError [ERR_ASSERTION]: 'a' != 'b'
+
+assert.fail(1, 2, undefined, '>');
+// AssertionError [ERR_ASSERTION]: 1 > 2
+
+assert.fail(1, 2, 'fail');
+// AssertionError [ERR_ASSERTION]: fail
+
+assert.fail(1, 2, 'whoops', '>');
+// AssertionError [ERR_ASSERTION]: whoops
+
+assert.fail(1, 2, new TypeError('need array'));
+// TypeError: need array
+--------------
+const assert = require('node:assert/strict');
+
+assert.fail('a', 'b');
+// AssertionError [ERR_ASSERTION]: 'a' != 'b'
+
+assert.fail(1, 2, undefined, '>');
+// AssertionError [ERR_ASSERTION]: 1 > 2
+
+assert.fail(1, 2, 'fail');
+// AssertionError [ERR_ASSERTION]: fail
+
+assert.fail(1, 2, 'whoops', '>');
+// AssertionError [ERR_ASSERTION]: whoops
+
+assert.fail(1, 2, new TypeError('need array'));
+// TypeError: need array
+```
+
+In the last three cases `actual`, `expected`, and `operator` have no
+influence on the error message.
+
+Example use of `stackStartFn` for truncating the exception's stacktrace:
+
+```mjs|cjs
+import assert from 'node:assert/strict';
+
+function suppressFrame() {
+ assert.fail('a', 'b', undefined, '!==', suppressFrame);
+}
+suppressFrame();
+// AssertionError [ERR_ASSERTION]: 'a' !== 'b'
+// at repl:1:1
+// at ContextifyScript.Script.runInThisContext (vm.js:44:33)
+// ...
+--------------
+const assert = require('node:assert/strict');
+
+function suppressFrame() {
+ assert.fail('a', 'b', undefined, '!==', suppressFrame);
+}
+suppressFrame();
+// AssertionError [ERR_ASSERTION]: 'a' !== 'b'
+// at repl:1:1
+// at ContextifyScript.Script.runInThisContext (vm.js:44:33)
+// ...
+```
+
+### `assert.ifError(value)`
+
+
+
+* `value` [`any`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Data_types)
+
+Throws `value` if `value` is not `undefined` or `null`. This is useful when
+testing the `error` argument in callbacks. The stack trace contains all frames
+from the error passed to `ifError()` including the potential new frames for
+`ifError()` itself.
+
+```mjs|cjs
+import assert from 'node:assert/strict';
+
+assert.ifError(null);
+// OK
+assert.ifError(0);
+// AssertionError [ERR_ASSERTION]: ifError got unwanted exception: 0
+assert.ifError('error');
+// AssertionError [ERR_ASSERTION]: ifError got unwanted exception: 'error'
+assert.ifError(new Error());
+// AssertionError [ERR_ASSERTION]: ifError got unwanted exception: Error
+
+// Create some random error frames.
+let err;
+(function errorFrame() {
+ err = new Error('test error');
+})();
+
+(function ifErrorFrame() {
+ assert.ifError(err);
+})();
+// AssertionError [ERR_ASSERTION]: ifError got unwanted exception: test error
+// at ifErrorFrame
+// at errorFrame
+--------------
+const assert = require('node:assert/strict');
+
+assert.ifError(null);
+// OK
+assert.ifError(0);
+// AssertionError [ERR_ASSERTION]: ifError got unwanted exception: 0
+assert.ifError('error');
+// AssertionError [ERR_ASSERTION]: ifError got unwanted exception: 'error'
+assert.ifError(new Error());
+// AssertionError [ERR_ASSERTION]: ifError got unwanted exception: Error
+
+// Create some random error frames.
+let err;
+(function errorFrame() {
+ err = new Error('test error');
+})();
+
+(function ifErrorFrame() {
+ assert.ifError(err);
+})();
+// AssertionError [ERR_ASSERTION]: ifError got unwanted exception: test error
+// at ifErrorFrame
+// at errorFrame
+```
+
+### `assert.match(string, regexp[, message])`
+
+
+
+* `string` [`string`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type)
+* `regexp` [`RegExp`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/RegExp)
+* `message` [`string`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type) | [`Error`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Error)
+
+Expects the `string` input to match the regular expression.
+
+```mjs|cjs
+import assert from 'node:assert/strict';
+
+assert.match('I will fail', /pass/);
+// AssertionError [ERR_ASSERTION]: The input did not match the regular ...
+
+assert.match(123, /pass/);
+// AssertionError [ERR_ASSERTION]: The "string" argument must be of type string.
+
+assert.match('I will pass', /pass/);
+// OK
+--------------
+const assert = require('node:assert/strict');
+
+assert.match('I will fail', /pass/);
+// AssertionError [ERR_ASSERTION]: The input did not match the regular ...
+
+assert.match(123, /pass/);
+// AssertionError [ERR_ASSERTION]: The "string" argument must be of type string.
+
+assert.match('I will pass', /pass/);
+// OK
+```
+
+If the values do not match, or if the `string` argument is of another type than
+`string`, an [`AssertionError`][] is thrown with a `message` property set equal
+to the value of the `message` parameter. If the `message` parameter is
+undefined, a default error message is assigned. If the `message` parameter is an
+instance of an [`Error`][] then it will be thrown instead of the
+[`AssertionError`][].
+
+### `assert.notDeepEqual(actual, expected[, message])`
+
+
+
+* `actual` [`any`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Data_types)
+* `expected` [`any`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Data_types)
+* `message` [`string`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type) | [`Error`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Error)
+
+**Strict assertion mode**
+
+An alias of [`assert.notDeepStrictEqual()`][].
+
+**Legacy assertion mode**
+
+
+
+Legacy: Use [`assert.notDeepStrictEqual()`][] instead.
+
+
+
+Tests for any deep inequality. Opposite of [`assert.deepEqual()`][].
+
+```mjs|cjs
+import assert from 'node:assert';
+
+const obj1 = {
+ a: {
+ b: 1
+ }
+};
+const obj2 = {
+ a: {
+ b: 2
+ }
+};
+const obj3 = {
+ a: {
+ b: 1
+ }
+};
+const obj4 = Object.create(obj1);
+
+assert.notDeepEqual(obj1, obj1);
+// AssertionError: { a: { b: 1 } } notDeepEqual { a: { b: 1 } }
+
+assert.notDeepEqual(obj1, obj2);
+// OK
+
+assert.notDeepEqual(obj1, obj3);
+// AssertionError: { a: { b: 1 } } notDeepEqual { a: { b: 1 } }
+
+assert.notDeepEqual(obj1, obj4);
+// OK
+--------------
+const assert = require('node:assert');
+
+const obj1 = {
+ a: {
+ b: 1
+ }
+};
+const obj2 = {
+ a: {
+ b: 2
+ }
+};
+const obj3 = {
+ a: {
+ b: 1
+ }
+};
+const obj4 = Object.create(obj1);
+
+assert.notDeepEqual(obj1, obj1);
+// AssertionError: { a: { b: 1 } } notDeepEqual { a: { b: 1 } }
+
+assert.notDeepEqual(obj1, obj2);
+// OK
+
+assert.notDeepEqual(obj1, obj3);
+// AssertionError: { a: { b: 1 } } notDeepEqual { a: { b: 1 } }
+
+assert.notDeepEqual(obj1, obj4);
+// OK
+```
+
+If the values are deeply equal, an [`AssertionError`][] is thrown with a
+`message` property set equal to the value of the `message` parameter. If the
+`message` parameter is undefined, a default error message is assigned. If the
+`message` parameter is an instance of an [`Error`][] then it will be thrown
+instead of the `AssertionError`.
+
+### `assert.notDeepStrictEqual(actual, expected[, message])`
+
+
+
+* `actual` [`any`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Data_types)
+* `expected` [`any`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Data_types)
+* `message` [`string`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type) | [`Error`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Error)
+
+Tests for deep strict inequality. Opposite of [`assert.deepStrictEqual()`][].
+
+```mjs|cjs
+import assert from 'node:assert/strict';
+
+assert.notDeepStrictEqual({ a: 1 }, { a: '1' });
+// OK
+--------------
+const assert = require('node:assert/strict');
+
+assert.notDeepStrictEqual({ a: 1 }, { a: '1' });
+// OK
+```
+
+If the values are deeply and strictly equal, an [`AssertionError`][] is thrown
+with a `message` property set equal to the value of the `message` parameter. If
+the `message` parameter is undefined, a default error message is assigned. If
+the `message` parameter is an instance of an [`Error`][] then it will be thrown
+instead of the [`AssertionError`][].
+
+### `assert.notEqual(actual, expected[, message])`
+
+
+
+* `actual` [`any`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Data_types)
+* `expected` [`any`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Data_types)
+* `message` [`string`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type) | [`Error`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Error)
+
+**Strict assertion mode**
+
+An alias of [`assert.notStrictEqual()`][].
+
+**Legacy assertion mode**
+
+
+
+Legacy: Use [`assert.notStrictEqual()`][] instead.
+
+
+
+Tests shallow, coercive inequality with the [`!=` operator][]. `NaN` is
+specially handled and treated as being identical if both sides are `NaN`.
+
+```mjs|cjs
+import assert from 'node:assert';
+
+assert.notEqual(1, 2);
+// OK
+
+assert.notEqual(1, 1);
+// AssertionError: 1 != 1
+
+assert.notEqual(1, '1');
+// AssertionError: 1 != '1'
+--------------
+const assert = require('node:assert');
+
+assert.notEqual(1, 2);
+// OK
+
+assert.notEqual(1, 1);
+// AssertionError: 1 != 1
+
+assert.notEqual(1, '1');
+// AssertionError: 1 != '1'
+```
+
+If the values are equal, an [`AssertionError`][] is thrown with a `message`
+property set equal to the value of the `message` parameter. If the `message`
+parameter is undefined, a default error message is assigned. If the `message`
+parameter is an instance of an [`Error`][] then it will be thrown instead of the
+`AssertionError`.
+
+### `assert.notStrictEqual(actual, expected[, message])`
+
+
+
+* `actual` [`any`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Data_types)
+* `expected` [`any`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Data_types)
+* `message` [`string`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type) | [`Error`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Error)
+
+Tests strict inequality between the `actual` and `expected` parameters as
+determined by [`Object.is()`][].
+
+```mjs|cjs
+import assert from 'node:assert/strict';
+
+assert.notStrictEqual(1, 2);
+// OK
+
+assert.notStrictEqual(1, 1);
+// AssertionError [ERR_ASSERTION]: Expected "actual" to be strictly unequal to:
+//
+// 1
+
+assert.notStrictEqual(1, '1');
+// OK
+--------------
+const assert = require('node:assert/strict');
+
+assert.notStrictEqual(1, 2);
+// OK
+
+assert.notStrictEqual(1, 1);
+// AssertionError [ERR_ASSERTION]: Expected "actual" to be strictly unequal to:
+//
+// 1
+
+assert.notStrictEqual(1, '1');
+// OK
+```
+
+If the values are strictly equal, an [`AssertionError`][] is thrown with a
+`message` property set equal to the value of the `message` parameter. If the
+`message` parameter is undefined, a default error message is assigned. If the
+`message` parameter is an instance of an [`Error`][] then it will be thrown
+instead of the `AssertionError`.
+
+### `assert.ok(value[, message])`
+
+
+
+* `value` [`any`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Data_types)
+* `message` [`string`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type) | [`Error`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Error)
+
+Tests if `value` is truthy. It is equivalent to
+`assert.equal(!!value, true, message)`.
+
+If `value` is not truthy, an [`AssertionError`][] is thrown with a `message`
+property set equal to the value of the `message` parameter. If the `message`
+parameter is `undefined`, a default error message is assigned. If the `message`
+parameter is an instance of an [`Error`][] then it will be thrown instead of the
+`AssertionError`.
+If no arguments are passed in at all `message` will be set to the string:
+``'No value argument passed to `assert.ok()`'``.
+
+Be aware that in the `repl` the error message will be different to the one
+thrown in a file! See below for further details.
+
+```mjs|cjs
+import assert from 'node:assert/strict';
+
+assert.ok(true);
+// OK
+assert.ok(1);
+// OK
+
+assert.ok();
+// AssertionError: No value argument passed to `assert.ok()`
+
+assert.ok(false, 'it\'s false');
+// AssertionError: it's false
+
+// In the repl:
+assert.ok(typeof 123 === 'string');
+// AssertionError: false == true
+
+// In a file (e.g. test.js):
+assert.ok(typeof 123 === 'string');
+// AssertionError: The expression evaluated to a falsy value:
+//
+// assert.ok(typeof 123 === 'string')
+
+assert.ok(false);
+// AssertionError: The expression evaluated to a falsy value:
+//
+// assert.ok(false)
+
+assert.ok(0);
+// AssertionError: The expression evaluated to a falsy value:
+//
+// assert.ok(0)
+--------------
+const assert = require('node:assert/strict');
+
+assert.ok(true);
+// OK
+assert.ok(1);
+// OK
+
+assert.ok();
+// AssertionError: No value argument passed to `assert.ok()`
+
+assert.ok(false, 'it\'s false');
+// AssertionError: it's false
+
+// In the repl:
+assert.ok(typeof 123 === 'string');
+// AssertionError: false == true
+
+// In a file (e.g. test.js):
+assert.ok(typeof 123 === 'string');
+// AssertionError: The expression evaluated to a falsy value:
+//
+// assert.ok(typeof 123 === 'string')
+
+assert.ok(false);
+// AssertionError: The expression evaluated to a falsy value:
+//
+// assert.ok(false)
+
+assert.ok(0);
+// AssertionError: The expression evaluated to a falsy value:
+//
+// assert.ok(0)
+```
+
+```mjs|cjs
+import assert from 'node:assert/strict';
+
+// Using `assert()` works the same:
+assert(0);
+// AssertionError: The expression evaluated to a falsy value:
+//
+// assert(0)
+--------------
+const assert = require('node:assert');
+
+// Using `assert()` works the same:
+assert(0);
+// AssertionError: The expression evaluated to a falsy value:
+//
+// assert(0)
+```
+
+### `assert.rejects(asyncFn[, error][, message])`
+
+
+
+* `asyncFn` [`Function`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Function) | [`Promise`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Promise)
+* `error` [`RegExp`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/RegExp) | [`Function`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Function) | [`Object`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object) | [`Error`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Error)
+* `message` [`string`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type)
+
+Awaits the `asyncFn` promise or, if `asyncFn` is a function, immediately
+calls the function and awaits the returned promise to complete. It will then
+check that the promise is rejected.
+
+If `asyncFn` is a function and it throws an error synchronously,
+`assert.rejects()` will return a rejected `Promise` with that error. If the
+function does not return a promise, `assert.rejects()` will return a rejected
+`Promise` with an [`ERR_INVALID_RETURN_VALUE`][] error. In both cases the error
+handler is skipped.
+
+Besides the async nature to await the completion behaves identically to
+[`assert.throws()`][].
+
+If specified, `error` can be a [`Class`][], [`RegExp`][], 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 `message` and
+`name` properties.
+
+If specified, `message` will be the message provided by the [`AssertionError`][]
+if the `asyncFn` fails to reject.
+
+```mjs|cjs
+import assert from 'node:assert/strict';
+
+await assert.rejects(
+ async () => {
+ throw new TypeError('Wrong value');
+ },
+ {
+ name: 'TypeError',
+ message: 'Wrong value'
+ }
+);
+--------------
+const assert = require('node:assert/strict');
+
+(async () => {
+ await assert.rejects(
+ async () => {
+ throw new TypeError('Wrong value');
+ },
+ {
+ name: 'TypeError',
+ message: 'Wrong value'
+ }
+ );
+})();
+```
+
+```mjs|cjs
+import assert from 'node:assert/strict';
+
+await assert.rejects(
+ async () => {
+ throw new TypeError('Wrong value');
+ },
+ (err) => {
+ assert.strictEqual(err.name, 'TypeError');
+ assert.strictEqual(err.message, 'Wrong value');
+ return true;
+ }
+);
+--------------
+const assert = require('node:assert/strict');
+
+(async () => {
+ await assert.rejects(
+ async () => {
+ throw new TypeError('Wrong value');
+ },
+ (err) => {
+ assert.strictEqual(err.name, 'TypeError');
+ assert.strictEqual(err.message, 'Wrong value');
+ return true;
+ }
+ );
+})();
+```
+
+```mjs|cjs
+import assert from 'node:assert/strict';
+
+assert.rejects(
+ Promise.reject(new Error('Wrong value')),
+ Error
+).then(() => {
+ // ...
+});
+--------------
+const assert = require('node:assert/strict');
+
+assert.rejects(
+ Promise.reject(new Error('Wrong value')),
+ Error
+).then(() => {
+ // ...
+});
+```
+
+`error` cannot be a string. If a string is provided as the second
+argument, then `error` is assumed to be omitted and the string will be used for
+`message` instead. This can lead to easy-to-miss mistakes. Please read the
+example in [`assert.throws()`][] carefully if using a string as the second
+argument gets considered.
+
+### `assert.strictEqual(actual, expected[, message])`
+
+
+
+* `actual` [`any`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Data_types)
+* `expected` [`any`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Data_types)
+* `message` [`string`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type) | [`Error`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Error)
+
+Tests strict equality between the `actual` and `expected` parameters as
+determined by [`Object.is()`][].
+
+```mjs|cjs
+import assert from 'node:assert/strict';
+
+assert.strictEqual(1, 2);
+// AssertionError [ERR_ASSERTION]: Expected inputs to be strictly equal:
+//
+// 1 !== 2
+
+assert.strictEqual(1, 1);
+// OK
+
+assert.strictEqual('Hello foobar', 'Hello World!');
+// AssertionError [ERR_ASSERTION]: Expected inputs to be strictly equal:
+// + actual - expected
+//
+// + 'Hello foobar'
+// - 'Hello World!'
+// ^
+
+const apples = 1;
+const oranges = 2;
+assert.strictEqual(apples, oranges, `apples ${apples} !== oranges ${oranges}`);
+// AssertionError [ERR_ASSERTION]: apples 1 !== oranges 2
+
+assert.strictEqual(1, '1', new TypeError('Inputs are not identical'));
+// TypeError: Inputs are not identical
+--------------
+const assert = require('node:assert/strict');
+
+assert.strictEqual(1, 2);
+// AssertionError [ERR_ASSERTION]: Expected inputs to be strictly equal:
+//
+// 1 !== 2
+
+assert.strictEqual(1, 1);
+// OK
+
+assert.strictEqual('Hello foobar', 'Hello World!');
+// AssertionError [ERR_ASSERTION]: Expected inputs to be strictly equal:
+// + actual - expected
+//
+// + 'Hello foobar'
+// - 'Hello World!'
+// ^
+
+const apples = 1;
+const oranges = 2;
+assert.strictEqual(apples, oranges, `apples ${apples} !== oranges ${oranges}`);
+// AssertionError [ERR_ASSERTION]: apples 1 !== oranges 2
+
+assert.strictEqual(1, '1', new TypeError('Inputs are not identical'));
+// TypeError: Inputs are not identical
+```
+
+If the values are not strictly equal, an [`AssertionError`][] is thrown with a
+`message` property set equal to the value of the `message` parameter. If the
+`message` parameter is undefined, a default error message is assigned. If the
+`message` parameter is an instance of an [`Error`][] then it will be thrown
+instead of the [`AssertionError`][].
+
+### `assert.throws(fn[, error][, message])`
+
+
+
+* `fn` [`Function`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Function)
+* `error` [`RegExp`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/RegExp) | [`Function`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Function) | [`Object`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object) | [`Error`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Error)
+* `message` [`string`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type)
+
+Expects the function `fn` to throw an error.
+
+If specified, `error` can be a [`Class`][], [`RegExp`][], 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 `message` and `name` properties. When
+using an object, it is also possible to use a regular expression, when
+validating against a string property. See below for examples.
+
+If specified, `message` will be appended to the message provided by the
+`AssertionError` if the `fn` call fails to throw or in case the error validation
+fails.
+
+Custom validation object/error instance:
+
+```mjs|cjs
+import assert from 'node:assert/strict';
+
+const err = new TypeError('Wrong value');
+err.code = 404;
+err.foo = 'bar';
+err.info = {
+ nested: true,
+ baz: 'text'
+};
+err.reg = /abc/i;
+
+assert.throws(
+ () => {
+ throw err;
+ },
+ {
+ name: 'TypeError',
+ message: 'Wrong value',
+ info: {
+ nested: true,
+ baz: 'text'
+ }
+ // Only properties on the validation object will be tested for.
+ // Using nested objects requires all properties to be present. Otherwise
+ // the validation is going to fail.
+ }
+);
+
+// Using regular expressions to validate error properties:
+assert.throws(
+ () => {
+ throw err;
+ },
+ {
+ // The `name` and `message` properties are strings and using regular
+ // expressions on those will match against the string. If they fail, an
+ // error is thrown.
+ name: /^TypeError$/,
+ message: /Wrong/,
+ foo: 'bar',
+ info: {
+ nested: true,
+ // It is not possible to use regular expressions for nested properties!
+ baz: 'text'
+ },
+ // The `reg` property contains a regular expression and only if the
+ // validation object contains an identical regular expression, it is going
+ // to pass.
+ reg: /abc/i
+ }
+);
+
+// Fails due to the different `message` and `name` properties:
+assert.throws(
+ () => {
+ const otherErr = new Error('Not found');
+ // Copy all enumerable properties from `err` to `otherErr`.
+ for (const [key, value] of Object.entries(err)) {
+ otherErr[key] = value;
+ }
+ throw otherErr;
+ },
+ // The error's `message` and `name` properties will also be checked when using
+ // an error as validation object.
+ err
+);
+--------------
+const assert = require('node:assert/strict');
+
+const err = new TypeError('Wrong value');
+err.code = 404;
+err.foo = 'bar';
+err.info = {
+ nested: true,
+ baz: 'text'
+};
+err.reg = /abc/i;
+
+assert.throws(
+ () => {
+ throw err;
+ },
+ {
+ name: 'TypeError',
+ message: 'Wrong value',
+ info: {
+ nested: true,
+ baz: 'text'
+ }
+ // Only properties on the validation object will be tested for.
+ // Using nested objects requires all properties to be present. Otherwise
+ // the validation is going to fail.
+ }
+);
+
+// Using regular expressions to validate error properties:
+assert.throws(
+ () => {
+ throw err;
+ },
+ {
+ // The `name` and `message` properties are strings and using regular
+ // expressions on those will match against the string. If they fail, an
+ // error is thrown.
+ name: /^TypeError$/,
+ message: /Wrong/,
+ foo: 'bar',
+ info: {
+ nested: true,
+ // It is not possible to use regular expressions for nested properties!
+ baz: 'text'
+ },
+ // The `reg` property contains a regular expression and only if the
+ // validation object contains an identical regular expression, it is going
+ // to pass.
+ reg: /abc/i
+ }
+);
+
+// Fails due to the different `message` and `name` properties:
+assert.throws(
+ () => {
+ const otherErr = new Error('Not found');
+ // Copy all enumerable properties from `err` to `otherErr`.
+ for (const [key, value] of Object.entries(err)) {
+ otherErr[key] = value;
+ }
+ throw otherErr;
+ },
+ // The error's `message` and `name` properties will also be checked when using
+ // an error as validation object.
+ err
+);
+```
+
+Validate instanceof using constructor:
+
+```mjs|cjs
+import assert from 'node:assert/strict';
+
+assert.throws(
+ () => {
+ throw new Error('Wrong value');
+ },
+ Error
+);
+--------------
+const assert = require('node:assert/strict');
+
+assert.throws(
+ () => {
+ throw new Error('Wrong value');
+ },
+ Error
+);
+```
+
+Validate error message using [`RegExp`][]:
+
+Using a regular expression runs `.toString` on the error object, and will
+therefore also include the error name.
+
+```mjs|cjs
+import assert from 'node:assert/strict';
+
+assert.throws(
+ () => {
+ throw new Error('Wrong value');
+ },
+ /^Error: Wrong value$/
+);
+--------------
+const assert = require('node:assert/strict');
+
+assert.throws(
+ () => {
+ throw new Error('Wrong value');
+ },
+ /^Error: Wrong value$/
+);
+```
+
+Custom error validation:
+
+The function must return `true` to indicate all internal validations passed.
+It will otherwise fail with an [`AssertionError`][].
+
+```mjs|cjs
+import assert from 'node:assert/strict';
+
+assert.throws(
+ () => {
+ throw new Error('Wrong value');
+ },
+ (err) => {
+ assert(err instanceof Error);
+ assert(/value/.test(err));
+ // Avoid returning anything from validation functions besides `true`.
+ // Otherwise, it's not clear what part of the validation failed. Instead,
+ // throw an error about the specific validation that failed (as done in this
+ // example) and add as much helpful debugging information to that error as
+ // possible.
+ return true;
+ },
+ 'unexpected error'
+);
+--------------
+const assert = require('node:assert/strict');
+
+assert.throws(
+ () => {
+ throw new Error('Wrong value');
+ },
+ (err) => {
+ assert(err instanceof Error);
+ assert(/value/.test(err));
+ // Avoid returning anything from validation functions besides `true`.
+ // Otherwise, it's not clear what part of the validation failed. Instead,
+ // throw an error about the specific validation that failed (as done in this
+ // example) and add as much helpful debugging information to that error as
+ // possible.
+ return true;
+ },
+ 'unexpected error'
+);
+```
+
+`error` cannot be a string. If a string is provided as the second
+argument, then `error` is assumed to be omitted and the string will be used for
+`message` instead. This can lead to easy-to-miss mistakes. Using the same
+message as the thrown error message is going to result in an
+`ERR_AMBIGUOUS_ARGUMENT` error. Please read the example below carefully if using
+a string as the second argument gets considered:
+
+```mjs|cjs
+import assert from 'node:assert/strict';
+
+function throwingFirst() {
+ throw new Error('First');
+}
+
+function throwingSecond() {
+ throw new Error('Second');
+}
+
+function notThrowing() {}
+
+// The second argument is a string and the input function threw an Error.
+// The first case will not throw as it does not match for the error message
+// thrown by the input function!
+assert.throws(throwingFirst, 'Second');
+// In the next example the message has no benefit over the message from the
+// error and since it is not clear if the user intended to actually match
+// against the error message, Node.js throws an `ERR_AMBIGUOUS_ARGUMENT` error.
+assert.throws(throwingSecond, 'Second');
+// TypeError [ERR_AMBIGUOUS_ARGUMENT]
+
+// The string is only used (as message) in case the function does not throw:
+assert.throws(notThrowing, 'Second');
+// AssertionError [ERR_ASSERTION]: Missing expected exception: Second
+
+// If it was intended to match for the error message do this instead:
+// It does not throw because the error messages match.
+assert.throws(throwingSecond, /Second$/);
+
+// If the error message does not match, an AssertionError is thrown.
+assert.throws(throwingFirst, /Second$/);
+// AssertionError [ERR_ASSERTION]
+--------------
+const assert = require('node:assert/strict');
+
+function throwingFirst() {
+ throw new Error('First');
+}
+
+function throwingSecond() {
+ throw new Error('Second');
+}
+
+function notThrowing() {}
+
+// The second argument is a string and the input function threw an Error.
+// The first case will not throw as it does not match for the error message
+// thrown by the input function!
+assert.throws(throwingFirst, 'Second');
+// In the next example the message has no benefit over the message from the
+// error and since it is not clear if the user intended to actually match
+// against the error message, Node.js throws an `ERR_AMBIGUOUS_ARGUMENT` error.
+assert.throws(throwingSecond, 'Second');
+// TypeError [ERR_AMBIGUOUS_ARGUMENT]
+
+// The string is only used (as message) in case the function does not throw:
+assert.throws(notThrowing, 'Second');
+// AssertionError [ERR_ASSERTION]: Missing expected exception: Second
+
+// If it was intended to match for the error message do this instead:
+// It does not throw because the error messages match.
+assert.throws(throwingSecond, /Second$/);
+
+// If the error message does not match, an AssertionError is thrown.
+assert.throws(throwingFirst, /Second$/);
+// AssertionError [ERR_ASSERTION]
+```
+
+Due to the confusing error-prone notation, avoid a string as the second
+argument.
+
+[Object wrappers]: https://developer.mozilla.org/en-US/docs/Glossary/Primitive#Primitive_wrapper_objects_in_JavaScript
+[Object.prototype.toString()]: https://tc39.github.io/ecma262/#sec-object.prototype.tostring
+[`!=` operator]: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Inequality
+[`===` operator]: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Strict_equality
+[`==` operator]: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Equality
+[`AssertionError`]: #class-assertassertionerror
+[`CallTracker`]: #class-assertcalltracker
+[`Class`]: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Classes
+[`ERR_INVALID_RETURN_VALUE`]: /api/v16/errors#err_invalid_return_value
+[`Error.captureStackTrace`]: /api/v16/errors#errorcapturestacktracetargetobject-constructoropt
+[`Error`]: /api/v16/errors#class-error
+[`Map`]: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Map
+[`Object.is()`]: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object/is
+[`RegExp`]: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Guide/Regular_Expressions
+[`Set`]: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Set
+[`Symbol`]: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Symbol
+[`TypeError`]: /api/v16/errors#class-typeerror
+[`WeakMap`]: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/WeakMap
+[`WeakSet`]: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/WeakSet
+[`assert.deepEqual()`]: #assertdeepequalactual-expected-message
+[`assert.deepStrictEqual()`]: #assertdeepstrictequalactual-expected-message
+[`assert.doesNotThrow()`]: #assertdoesnotthrowfn-error-message
+[`assert.equal()`]: #assertequalactual-expected-message
+[`assert.notDeepEqual()`]: #assertnotdeepequalactual-expected-message
+[`assert.notDeepStrictEqual()`]: #assertnotdeepstrictequalactual-expected-message
+[`assert.notEqual()`]: #assertnotequalactual-expected-message
+[`assert.notStrictEqual()`]: #assertnotstrictequalactual-expected-message
+[`assert.ok()`]: #assertokvalue-message
+[`assert.strictEqual()`]: #assertstrictequalactual-expected-message
+[`assert.throws()`]: #assertthrowsfn-error-message
+[`getColorDepth()`]: /api/v16/tty#writestreamgetcolordepthenv
+[`process.on('exit')`]: /api/v16/process#event-exit
+[`tracker.calls()`]: #trackercallsfn-exact
+[`tracker.verify()`]: #trackerverify
+[enumerable "own" properties]: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Enumerability_and_ownership_of_properties
+[prototype-spec]: https://tc39.github.io/ecma262/#sec-ordinary-object-internal-methods-and-internal-slots
diff --git a/content/api/v16/async_context.en.md b/content/api/v16/async_context.en.md
new file mode 100644
index 0000000000..45990b68f9
--- /dev/null
+++ b/content/api/v16/async_context.en.md
@@ -0,0 +1,759 @@
+---
+title: 'async_context'
+displayTitle: 'Asynchronous context tracking'
+category: 'api'
+version: 'v16'
+---
+
+
+
+
+
+Stable
+
+
+
+
+
+### Introduction
+
+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.
+
+The `AsyncLocalStorage` and `AsyncResource` classes are part of the
+`node:async_hooks` module:
+
+```mjs|cjs
+import { AsyncLocalStorage, AsyncResource } from 'node:async_hooks';
+--------------
+const { AsyncLocalStorage, AsyncResource } = require('node:async_hooks');
+```
+
+### `AsyncLocalStorage`
+
+
+
+This class creates stores that stay coherent through asynchronous operations.
+
+While you can create your own implementation on top of the `node:async_hooks`
+module, `AsyncLocalStorage` should be preferred as it is a performant and memory
+safe implementation that involves significant optimizations that are non-obvious
+to implement.
+
+The following example uses `AsyncLocalStorage` to build a simple logger
+that assigns IDs to incoming HTTP requests and includes them in messages
+logged within each request.
+
+```mjs|cjs
+import http from 'node:http';
+import { AsyncLocalStorage } from 'node:async_hooks';
+
+const asyncLocalStorage = new AsyncLocalStorage();
+
+function logWithId(msg) {
+ const id = asyncLocalStorage.getStore();
+ console.log(`${id !== undefined ? id : '-'}:`, msg);
+}
+
+let idSeq = 0;
+http.createServer((req, res) => {
+ asyncLocalStorage.run(idSeq++, () => {
+ logWithId('start');
+ // Imagine any chain of async operations here
+ setImmediate(() => {
+ logWithId('finish');
+ res.end();
+ });
+ });
+}).listen(8080);
+
+http.get('http://localhost:8080');
+http.get('http://localhost:8080');
+// Prints:
+// 0: start
+// 1: start
+// 0: finish
+// 1: finish
+--------------
+const http = require('node:http');
+const { AsyncLocalStorage } = require('node:async_hooks');
+
+const asyncLocalStorage = new AsyncLocalStorage();
+
+function logWithId(msg) {
+ const id = asyncLocalStorage.getStore();
+ console.log(`${id !== undefined ? id : '-'}:`, msg);
+}
+
+let idSeq = 0;
+http.createServer((req, res) => {
+ asyncLocalStorage.run(idSeq++, () => {
+ logWithId('start');
+ // Imagine any chain of async operations here
+ setImmediate(() => {
+ logWithId('finish');
+ res.end();
+ });
+ });
+}).listen(8080);
+
+http.get('http://localhost:8080');
+http.get('http://localhost:8080');
+// Prints:
+// 0: start
+// 1: start
+// 0: finish
+// 1: finish
+```
+
+Each instance of `AsyncLocalStorage` maintains an independent storage context.
+Multiple instances can safely exist simultaneously without risk of interfering
+with each other's data.
+
+#### `new AsyncLocalStorage()`
+
+
+
+Creates a new instance of `AsyncLocalStorage`. Store is only provided within a
+`run()` call or after an `enterWith()` call.
+
+#### `asyncLocalStorage.disable()`
+
+
+
+
+
+Experimental
+
+
+
+Disables the instance of `AsyncLocalStorage`. All subsequent calls
+to `asyncLocalStorage.getStore()` will return `undefined` until
+`asyncLocalStorage.run()` or `asyncLocalStorage.enterWith()` is called again.
+
+When calling `asyncLocalStorage.disable()`, all current contexts linked to the
+instance will be exited.
+
+Calling `asyncLocalStorage.disable()` is required before the
+`asyncLocalStorage` can be garbage collected. This does not apply to stores
+provided by the `asyncLocalStorage`, as those objects are garbage collected
+along with the corresponding async resources.
+
+Use this method when the `asyncLocalStorage` is not in use anymore
+in the current process.
+
+#### `asyncLocalStorage.getStore()`
+
+
+
+* Returns: [`any`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Data_types)
+
+Returns the current store.
+If called outside of an asynchronous context initialized by
+calling `asyncLocalStorage.run()` or `asyncLocalStorage.enterWith()`, it
+returns `undefined`.
+
+#### `asyncLocalStorage.enterWith(store)`
+
+
+
+
+
+Experimental
+
+
+
+* `store` [`any`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Data_types)
+
+Transitions into the context for the remainder of the current
+synchronous execution and then persists the store through any following
+asynchronous calls.
+
+Example:
+
+```js
+const store = { id: 1 };
+// Replaces previous store with the given store object
+asyncLocalStorage.enterWith(store);
+asyncLocalStorage.getStore(); // Returns the store object
+someAsyncOperation(() => {
+ asyncLocalStorage.getStore(); // Returns the same object
+});
+```
+
+This transition will continue for the _entire_ 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 `AsyncResource`. That is why
+`run()` should be preferred over `enterWith()` unless there are strong reasons
+to use the latter method.
+
+```js
+const store = { id: 1 };
+
+emitter.on('my-event', () => {
+ asyncLocalStorage.enterWith(store);
+});
+emitter.on('my-event', () => {
+ asyncLocalStorage.getStore(); // Returns the same object
+});
+
+asyncLocalStorage.getStore(); // Returns undefined
+emitter.emit('my-event');
+asyncLocalStorage.getStore(); // Returns the same object
+```
+
+#### `asyncLocalStorage.run(store, callback[, ...args])`
+
+
+
+* `store` [`any`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Data_types)
+* `callback` [`Function`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Function)
+* `...args` [`any`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Data_types)
+
+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.
+
+The optional `args` are passed to the callback function.
+
+If the callback function throws an error, the error is thrown by `run()` too.
+The stacktrace is not impacted by this call and the context is exited.
+
+Example:
+
+```js
+const store = { id: 2 };
+try {
+ asyncLocalStorage.run(store, () => {
+ asyncLocalStorage.getStore(); // Returns the store object
+ setTimeout(() => {
+ asyncLocalStorage.getStore(); // Returns the store object
+ }, 200);
+ throw new Error();
+ });
+} catch (e) {
+ asyncLocalStorage.getStore(); // Returns undefined
+ // The error will be caught here
+}
+```
+
+#### `asyncLocalStorage.exit(callback[, ...args])`
+
+
+
+
+
+Experimental
+
+
+
+* `callback` [`Function`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Function)
+* `...args` [`any`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Data_types)
+
+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 `getStore()`
+call done within the callback function will always return `undefined`.
+
+The optional `args` are passed to the callback function.
+
+If the callback function throws an error, the error is thrown by `exit()` too.
+The stacktrace is not impacted by this call and the context is re-entered.
+
+Example:
+
+```js
+// Within a call to run
+try {
+ asyncLocalStorage.getStore(); // Returns the store object or value
+ asyncLocalStorage.exit(() => {
+ asyncLocalStorage.getStore(); // Returns undefined
+ throw new Error();
+ });
+} catch (e) {
+ asyncLocalStorage.getStore(); // Returns the same object or value
+ // The error will be caught here
+}
+```
+
+#### Usage with `async/await`
+
+If, within an async function, only one `await` call is to run within a context,
+the following pattern should be used:
+
+```js
+async function fn() {
+ await asyncLocalStorage.run(new Map(), () => {
+ asyncLocalStorage.getStore().set('key', value);
+ return foo(); // The return value of foo will be awaited
+ });
+}
+```
+
+In this example, the store is only available in the callback function and the
+functions called by `foo`. Outside of `run`, calling `getStore` will return
+`undefined`.
+
+#### Troubleshooting: Context loss
+
+In most cases, `AsyncLocalStorage` works without issues. In rare situations, the
+current store is lost in one of the asynchronous operations.
+
+If your code is callback-based, it is enough to promisify it with
+[`util.promisify()`][] so it starts working with native promises.
+
+If you need to use a callback-based API or your code assumes
+a custom thenable implementation, use the [`AsyncResource`][] 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 `asyncLocalStorage.getStore()` after the calls you suspect are responsible
+for the loss. When the code logs `undefined`, the last callback called is
+probably responsible for the context loss.
+
+### `AsyncResource`
+
+
+
+The class `AsyncResource` is designed to be extended by the embedder's async
+resources. Using this, users can easily trigger the lifetime events of their
+own resources.
+
+The `init` hook will trigger when an `AsyncResource` is instantiated.
+
+The following is an overview of the `AsyncResource` API.
+
+```mjs|cjs
+import { AsyncResource, executionAsyncId } from 'node:async_hooks';
+
+// AsyncResource() is meant to be extended. Instantiating a
+// new AsyncResource() also triggers init. If triggerAsyncId is omitted then
+// async_hook.executionAsyncId() is used.
+const asyncResource = new AsyncResource(
+ type, { triggerAsyncId: executionAsyncId(), requireManualDestroy: false }
+);
+
+// Run a function in the execution context of the resource. This will
+// * establish the context of the resource
+// * trigger the AsyncHooks before callbacks
+// * call the provided function `fn` with the supplied arguments
+// * trigger the AsyncHooks after callbacks
+// * restore the original execution context
+asyncResource.runInAsyncScope(fn, thisArg, ...args);
+
+// Call AsyncHooks destroy callbacks.
+asyncResource.emitDestroy();
+
+// Return the unique ID assigned to the AsyncResource instance.
+asyncResource.asyncId();
+
+// Return the trigger ID for the AsyncResource instance.
+asyncResource.triggerAsyncId();
+--------------
+const { AsyncResource, executionAsyncId } = require('node:async_hooks');
+
+// AsyncResource() is meant to be extended. Instantiating a
+// new AsyncResource() also triggers init. If triggerAsyncId is omitted then
+// async_hook.executionAsyncId() is used.
+const asyncResource = new AsyncResource(
+ type, { triggerAsyncId: executionAsyncId(), requireManualDestroy: false }
+);
+
+// Run a function in the execution context of the resource. This will
+// * establish the context of the resource
+// * trigger the AsyncHooks before callbacks
+// * call the provided function `fn` with the supplied arguments
+// * trigger the AsyncHooks after callbacks
+// * restore the original execution context
+asyncResource.runInAsyncScope(fn, thisArg, ...args);
+
+// Call AsyncHooks destroy callbacks.
+asyncResource.emitDestroy();
+
+// Return the unique ID assigned to the AsyncResource instance.
+asyncResource.asyncId();
+
+// Return the trigger ID for the AsyncResource instance.
+asyncResource.triggerAsyncId();
+```
+
+#### `new AsyncResource(type[, options])`
+
+* `type` [`string`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type) The type of async event.
+* `options` [`Object`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object)
+ * `triggerAsyncId` [`number`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type) The ID of the execution context that created this
+ async event. **Default:** `executionAsyncId()`.
+ * `requireManualDestroy` [`boolean`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Boolean_type) If set to `true`, disables `emitDestroy`
+ when the object is garbage collected. This usually does not need to be set
+ (even if `emitDestroy` is called manually), unless the resource's `asyncId`
+ is retrieved and the sensitive API's `emitDestroy` is called with it.
+ When set to `false`, the `emitDestroy` call on garbage collection
+ will only take place if there is at least one active `destroy` hook.
+ **Default:** `false`.
+
+Example usage:
+
+```js
+class DBQuery extends AsyncResource {
+ constructor(db) {
+ super('DBQuery');
+ this.db = db;
+ }
+
+ getInfo(query, callback) {
+ this.db.get(query, (err, data) => {
+ this.runInAsyncScope(callback, null, err, data);
+ });
+ }
+
+ close() {
+ this.db = null;
+ this.emitDestroy();
+ }
+}
+```
+
+#### Static method: `AsyncResource.bind(fn[, type[, thisArg]])`
+
+
+
+* `fn` [`Function`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Function) The function to bind to the current execution context.
+* `type` [`string`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type) An optional name to associate with the underlying
+ `AsyncResource`.
+* `thisArg` [`any`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Data_types)
+
+Binds the given function to the current execution context.
+
+The returned function will have an `asyncResource` property referencing
+the `AsyncResource` to which the function is bound.
+
+#### `asyncResource.bind(fn[, thisArg])`
+
+
+
+* `fn` [`Function`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Function) The function to bind to the current `AsyncResource`.
+* `thisArg` [`any`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Data_types)
+
+Binds the given function to execute to this `AsyncResource`'s scope.
+
+The returned function will have an `asyncResource` property referencing
+the `AsyncResource` to which the function is bound.
+
+#### `asyncResource.runInAsyncScope(fn[, thisArg, ...args])`
+
+
+
+* `fn` [`Function`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Function) The function to call in the execution context of this async
+ resource.
+* `thisArg` [`any`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Data_types) The receiver to be used for the function call.
+* `...args` [`any`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Data_types) Optional arguments to pass to the function.
+
+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.
+
+#### `asyncResource.emitDestroy()`
+
+* Returns: [`AsyncResource`](/api/v16/async_hooks#asyncresource) A reference to `asyncResource`.
+
+Call all `destroy` hooks. This should only ever be called once. An error will
+be thrown if it is called more than once. This **must** be manually called. If
+the resource is left to be collected by the GC then the `destroy` hooks will
+never be called.
+
+#### `asyncResource.asyncId()`
+
+* Returns: [`number`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type) The unique `asyncId` assigned to the resource.
+
+#### `asyncResource.triggerAsyncId()`
+
+* Returns: [`number`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type) The same `triggerAsyncId` that is passed to the
+ `AsyncResource` constructor.
+
+
+
+#### Using `AsyncResource` for a `Worker` thread pool
+
+The following example shows how to use the `AsyncResource` class to properly
+provide async tracking for a [`Worker`][] pool. Other resource pools, such as
+database connection pools, can follow a similar model.
+
+Assuming that the task is adding two numbers, using a file named
+`task_processor.js` with the following content:
+
+```mjs|cjs
+import { parentPort } from 'node:worker_threads';
+parentPort.on('message', (task) => {
+ parentPort.postMessage(task.a + task.b);
+});
+--------------
+const { parentPort } = require('node:worker_threads');
+parentPort.on('message', (task) => {
+ parentPort.postMessage(task.a + task.b);
+});
+```
+
+a Worker pool around it could use the following structure:
+
+```mjs|cjs
+import { AsyncResource } from 'node:async_hooks';
+import { EventEmitter } from 'node:events';
+import path from 'node:path';
+import { Worker } from 'node:worker_threads';
+
+const kTaskInfo = Symbol('kTaskInfo');
+const kWorkerFreedEvent = Symbol('kWorkerFreedEvent');
+
+class WorkerPoolTaskInfo extends AsyncResource {
+ constructor(callback) {
+ super('WorkerPoolTaskInfo');
+ this.callback = callback;
+ }
+
+ done(err, result) {
+ this.runInAsyncScope(this.callback, null, err, result);
+ this.emitDestroy(); // `TaskInfo`s are used only once.
+ }
+}
+
+export default class WorkerPool extends EventEmitter {
+ constructor(numThreads) {
+ super();
+ this.numThreads = numThreads;
+ this.workers = [];
+ this.freeWorkers = [];
+ this.tasks = [];
+
+ for (let i = 0; i < numThreads; i++)
+ this.addNewWorker();
+
+ // Any time the kWorkerFreedEvent is emitted, dispatch
+ // the next task pending in the queue, if any.
+ this.on(kWorkerFreedEvent, () => {
+ if (this.tasks.length > 0) {
+ const { task, callback } = this.tasks.shift();
+ this.runTask(task, callback);
+ }
+ });
+ }
+
+ addNewWorker() {
+ const worker = new Worker(new URL('task_processer.js', import.meta.url));
+ worker.on('message', (result) => {
+ // In case of success: Call the callback that was passed to `runTask`,
+ // remove the `TaskInfo` associated with the Worker, and mark it as free
+ // again.
+ worker[kTaskInfo].done(null, result);
+ worker[kTaskInfo] = null;
+ this.freeWorkers.push(worker);
+ this.emit(kWorkerFreedEvent);
+ });
+ worker.on('error', (err) => {
+ // In case of an uncaught exception: Call the callback that was passed to
+ // `runTask` with the error.
+ if (worker[kTaskInfo])
+ worker[kTaskInfo].done(err, null);
+ else
+ this.emit('error', err);
+ // Remove the worker from the list and start a new Worker to replace the
+ // current one.
+ this.workers.splice(this.workers.indexOf(worker), 1);
+ this.addNewWorker();
+ });
+ this.workers.push(worker);
+ this.freeWorkers.push(worker);
+ this.emit(kWorkerFreedEvent);
+ }
+
+ runTask(task, callback) {
+ if (this.freeWorkers.length === 0) {
+ // No free threads, wait until a worker thread becomes free.
+ this.tasks.push({ task, callback });
+ return;
+ }
+
+ const worker = this.freeWorkers.pop();
+ worker[kTaskInfo] = new WorkerPoolTaskInfo(callback);
+ worker.postMessage(task);
+ }
+
+ close() {
+ for (const worker of this.workers) worker.terminate();
+ }
+}
+--------------
+const { AsyncResource } = require('node:async_hooks');
+const { EventEmitter } = require('node:events');
+const path = require('node:path');
+const { Worker } = require('node:worker_threads');
+
+const kTaskInfo = Symbol('kTaskInfo');
+const kWorkerFreedEvent = Symbol('kWorkerFreedEvent');
+
+class WorkerPoolTaskInfo extends AsyncResource {
+ constructor(callback) {
+ super('WorkerPoolTaskInfo');
+ this.callback = callback;
+ }
+
+ done(err, result) {
+ this.runInAsyncScope(this.callback, null, err, result);
+ this.emitDestroy(); // `TaskInfo`s are used only once.
+ }
+}
+
+class WorkerPool extends EventEmitter {
+ constructor(numThreads) {
+ super();
+ this.numThreads = numThreads;
+ this.workers = [];
+ this.freeWorkers = [];
+ this.tasks = [];
+
+ for (let i = 0; i < numThreads; i++)
+ this.addNewWorker();
+
+ // Any time the kWorkerFreedEvent is emitted, dispatch
+ // the next task pending in the queue, if any.
+ this.on(kWorkerFreedEvent, () => {
+ if (this.tasks.length > 0) {
+ const { task, callback } = this.tasks.shift();
+ this.runTask(task, callback);
+ }
+ });
+ }
+
+ addNewWorker() {
+ const worker = new Worker(path.resolve(__dirname, 'task_processor.js'));
+ worker.on('message', (result) => {
+ // In case of success: Call the callback that was passed to `runTask`,
+ // remove the `TaskInfo` associated with the Worker, and mark it as free
+ // again.
+ worker[kTaskInfo].done(null, result);
+ worker[kTaskInfo] = null;
+ this.freeWorkers.push(worker);
+ this.emit(kWorkerFreedEvent);
+ });
+ worker.on('error', (err) => {
+ // In case of an uncaught exception: Call the callback that was passed to
+ // `runTask` with the error.
+ if (worker[kTaskInfo])
+ worker[kTaskInfo].done(err, null);
+ else
+ this.emit('error', err);
+ // Remove the worker from the list and start a new Worker to replace the
+ // current one.
+ this.workers.splice(this.workers.indexOf(worker), 1);
+ this.addNewWorker();
+ });
+ this.workers.push(worker);
+ this.freeWorkers.push(worker);
+ this.emit(kWorkerFreedEvent);
+ }
+
+ runTask(task, callback) {
+ if (this.freeWorkers.length === 0) {
+ // No free threads, wait until a worker thread becomes free.
+ this.tasks.push({ task, callback });
+ return;
+ }
+
+ const worker = this.freeWorkers.pop();
+ worker[kTaskInfo] = new WorkerPoolTaskInfo(callback);
+ worker.postMessage(task);
+ }
+
+ close() {
+ for (const worker of this.workers) worker.terminate();
+ }
+}
+
+module.exports = WorkerPool;
+```
+
+Without the explicit tracking added by the `WorkerPoolTaskInfo` objects,
+it would appear that the callbacks are associated with the individual `Worker`
+objects. However, the creation of the `Worker`s is not associated with the
+creation of the tasks and does not provide information about when tasks
+were scheduled.
+
+This pool could be used as follows:
+
+```mjs|cjs
+import WorkerPool from './worker_pool.js';
+import os from 'node:os';
+
+const pool = new WorkerPool(os.cpus().length);
+
+let finished = 0;
+for (let i = 0; i < 10; i++) {
+ pool.runTask({ a: 42, b: 100 }, (err, result) => {
+ console.log(i, err, result);
+ if (++finished === 10)
+ pool.close();
+ });
+}
+--------------
+const WorkerPool = require('./worker_pool.js');
+const os = require('node:os');
+
+const pool = new WorkerPool(os.cpus().length);
+
+let finished = 0;
+for (let i = 0; i < 10; i++) {
+ pool.runTask({ a: 42, b: 100 }, (err, result) => {
+ console.log(i, err, result);
+ if (++finished === 10)
+ pool.close();
+ });
+}
+```
+
+#### Integrating `AsyncResource` with `EventEmitter`
+
+Event listeners triggered by an [`EventEmitter`][] may be run in a different
+execution context than the one that was active when `eventEmitter.on()` was
+called.
+
+The following example shows how to use the `AsyncResource` class to properly
+associate an event listener with the correct execution context. The same
+approach can be applied to a [`Stream`][] or a similar event-driven class.
+
+```mjs|cjs
+import { createServer } from 'node:http';
+import { AsyncResource, executionAsyncId } from 'node:async_hooks';
+
+const server = createServer((req, res) => {
+ req.on('close', AsyncResource.bind(() => {
+ // Execution context is bound to the current outer scope.
+ }));
+ req.on('close', () => {
+ // Execution context is bound to the scope that caused 'close' to emit.
+ });
+ res.end();
+}).listen(3000);
+--------------
+const { createServer } = require('node:http');
+const { AsyncResource, executionAsyncId } = require('node:async_hooks');
+
+const server = createServer((req, res) => {
+ req.on('close', AsyncResource.bind(() => {
+ // Execution context is bound to the current outer scope.
+ }));
+ req.on('close', () => {
+ // Execution context is bound to the scope that caused 'close' to emit.
+ });
+ res.end();
+}).listen(3000);
+```
+
+[`AsyncResource`]: #class-asyncresource
+[`EventEmitter`]: /api/v16/events#class-eventemitter
+[`Stream`]: /api/v16/stream#stream
+[`Worker`]: worker_threads.md#class-worker
+[`util.promisify()`]: /api/v16/util#utilpromisifyoriginal
diff --git a/content/api/v16/async_hooks.en.md b/content/api/v16/async_hooks.en.md
new file mode 100644
index 0000000000..cc13fc86a0
--- /dev/null
+++ b/content/api/v16/async_hooks.en.md
@@ -0,0 +1,844 @@
+---
+title: 'async_hooks'
+displayTitle: 'Async hooks'
+category: 'api'
+version: 'v16'
+---
+
+
+
+
+
+Experimental
+
+
+
+
+
+The `node:async_hooks` module provides an API to track asynchronous resources.
+It can be accessed using:
+
+```mjs|cjs
+import async_hooks from 'node:async_hooks';
+--------------
+const async_hooks = require('node:async_hooks');
+```
+
+### Terminology
+
+An asynchronous resource represents an object with an associated callback.
+This callback may be called multiple times, such as the `'connection'`
+event in `net.createServer()`, or just a single time like in `fs.open()`.
+A resource can also be closed before the callback is called. `AsyncHook` does
+not explicitly distinguish between these different cases but will represent them
+as the abstract concept that is a resource.
+
+If [`Worker`][]s are used, each thread has an independent `async_hooks`
+interface, and each thread will use a new set of async IDs.
+
+### Overview
+
+Following is a simple overview of the public API.
+
+```mjs|cjs
+import async_hooks from 'node:async_hooks';
+
+// Return the ID of the current execution context.
+const eid = async_hooks.executionAsyncId();
+
+// Return the ID of the handle responsible for triggering the callback of the
+// current execution scope to call.
+const tid = async_hooks.triggerAsyncId();
+
+// Create a new AsyncHook instance. All of these callbacks are optional.
+const asyncHook =
+ async_hooks.createHook({ init, before, after, destroy, promiseResolve });
+
+// Allow callbacks of this AsyncHook instance to call. This is not an implicit
+// action after running the constructor, and must be explicitly run to begin
+// executing callbacks.
+asyncHook.enable();
+
+// Disable listening for new asynchronous events.
+asyncHook.disable();
+
+//
+// The following are the callbacks that can be passed to createHook().
+//
+
+// init() is called during object construction. The resource may not have
+// completed construction when this callback runs. Therefore, all fields of the
+// resource referenced by "asyncId" may not have been populated.
+function init(asyncId, type, triggerAsyncId, resource) { }
+
+// before() is called just before the resource's callback is called. It can be
+// called 0-N times for handles (such as TCPWrap), and will be called exactly 1
+// time for requests (such as FSReqCallback).
+function before(asyncId) { }
+
+// after() is called just after the resource's callback has finished.
+function after(asyncId) { }
+
+// destroy() is called when the resource is destroyed.
+function destroy(asyncId) { }
+
+// promiseResolve() is called only for promise resources, when the
+// resolve() function passed to the Promise constructor is invoked
+// (either directly or through other means of resolving a promise).
+function promiseResolve(asyncId) { }
+--------------
+const async_hooks = require('node:async_hooks');
+
+// Return the ID of the current execution context.
+const eid = async_hooks.executionAsyncId();
+
+// Return the ID of the handle responsible for triggering the callback of the
+// current execution scope to call.
+const tid = async_hooks.triggerAsyncId();
+
+// Create a new AsyncHook instance. All of these callbacks are optional.
+const asyncHook =
+ async_hooks.createHook({ init, before, after, destroy, promiseResolve });
+
+// Allow callbacks of this AsyncHook instance to call. This is not an implicit
+// action after running the constructor, and must be explicitly run to begin
+// executing callbacks.
+asyncHook.enable();
+
+// Disable listening for new asynchronous events.
+asyncHook.disable();
+
+//
+// The following are the callbacks that can be passed to createHook().
+//
+
+// init() is called during object construction. The resource may not have
+// completed construction when this callback runs. Therefore, all fields of the
+// resource referenced by "asyncId" may not have been populated.
+function init(asyncId, type, triggerAsyncId, resource) { }
+
+// before() is called just before the resource's callback is called. It can be
+// called 0-N times for handles (such as TCPWrap), and will be called exactly 1
+// time for requests (such as FSReqCallback).
+function before(asyncId) { }
+
+// after() is called just after the resource's callback has finished.
+function after(asyncId) { }
+
+// destroy() is called when the resource is destroyed.
+function destroy(asyncId) { }
+
+// promiseResolve() is called only for promise resources, when the
+// resolve() function passed to the Promise constructor is invoked
+// (either directly or through other means of resolving a promise).
+function promiseResolve(asyncId) { }
+```
+
+### `async_hooks.createHook(callbacks)`
+
+
+
+* `callbacks` [`Object`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object) The [Hook Callbacks][] to register
+ * `init` [`Function`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Function) The [`init` callback][].
+ * `before` [`Function`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Function) The [`before` callback][].
+ * `after` [`Function`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Function) The [`after` callback][].
+ * `destroy` [`Function`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Function) The [`destroy` callback][].
+ * `promiseResolve` [`Function`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Function) The [`promiseResolve` callback][].
+* Returns: [`AsyncHook`](/api/v16/async_hooks#async_hookscreatehookcallbacks) Instance used for disabling and enabling hooks
+
+Registers functions to be called for different lifetime events of each async
+operation.
+
+The callbacks `init()`/`before()`/`after()`/`destroy()` are called for the
+respective asynchronous event during a resource's lifetime.
+
+All callbacks are optional. For example, if only resource cleanup needs to
+be tracked, then only the `destroy` callback needs to be passed. The
+specifics of all functions that can be passed to `callbacks` is in the
+[Hook Callbacks][] section.
+
+```mjs|cjs
+import { createHook } from 'node:async_hooks';
+
+const asyncHook = createHook({
+ init(asyncId, type, triggerAsyncId, resource) { },
+ destroy(asyncId) { }
+});
+--------------
+const async_hooks = require('node:async_hooks');
+
+const asyncHook = async_hooks.createHook({
+ init(asyncId, type, triggerAsyncId, resource) { },
+ destroy(asyncId) { }
+});
+```
+
+The callbacks will be inherited via the prototype chain:
+
+```js
+class MyAsyncCallbacks {
+ init(asyncId, type, triggerAsyncId, resource) { }
+ destroy(asyncId) {}
+}
+
+class MyAddedCallbacks extends MyAsyncCallbacks {
+ before(asyncId) { }
+ after(asyncId) { }
+}
+
+const asyncHook = async_hooks.createHook(new MyAddedCallbacks());
+```
+
+Because promises are asynchronous resources whose lifecycle is tracked
+via the async hooks mechanism, the `init()`, `before()`, `after()`, and
+`destroy()` callbacks _must not_ be async functions that return promises.
+
+#### Error handling
+
+If any `AsyncHook` callbacks throw, the application will print the stack trace
+and exit. The exit path does follow that of an uncaught exception, but
+all `'uncaughtException'` listeners are removed, thus forcing the process to
+exit. The `'exit'` callbacks will still be called unless the application is run
+with `--abort-on-uncaught-exception`, in which case a stack trace will be
+printed and the application exits, leaving a core file.
+
+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.
+
+#### Printing in `AsyncHook` callbacks
+
+Because printing to the console is an asynchronous operation, `console.log()`
+will cause `AsyncHook` callbacks to be called. Using `console.log()` or
+similar asynchronous operations inside an `AsyncHook` callback function will
+cause an infinite recursion. An easy solution to this when debugging is to use a
+synchronous logging operation such as `fs.writeFileSync(file, msg, flag)`.
+This will print to the file and will not invoke `AsyncHook` recursively because
+it is synchronous.
+
+```mjs|cjs
+import { writeFileSync } from 'node:fs';
+import { format } from 'node:util';
+
+function debug(...args) {
+ // Use a function like this one when debugging inside an AsyncHook callback
+ writeFileSync('log.out', `${format(...args)}\n`, { flag: 'a' });
+}
+--------------
+const fs = require('node:fs');
+const util = require('node:util');
+
+function debug(...args) {
+ // Use a function like this one when debugging inside an AsyncHook callback
+ fs.writeFileSync('log.out', `${util.format(...args)}\n`, { flag: 'a' });
+}
+```
+
+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 `AsyncHook` itself. The logging should then be skipped when
+it was the logging itself that caused the `AsyncHook` callback to be called. By
+doing this, the otherwise infinite recursion is broken.
+
+### `AsyncHook`
+
+The class `AsyncHook` exposes an interface for tracking lifetime events
+of asynchronous operations.
+
+#### `asyncHook.enable()`
+
+* Returns: [`AsyncHook`](/api/v16/async_hooks#async_hookscreatehookcallbacks) A reference to `asyncHook`.
+
+Enable the callbacks for a given `AsyncHook` instance. If no callbacks are
+provided, enabling is a no-op.
+
+The `AsyncHook` instance is disabled by default. If the `AsyncHook` instance
+should be enabled immediately after creation, the following pattern can be used.
+
+```mjs|cjs
+import { createHook } from 'node:async_hooks';
+
+const hook = createHook(callbacks).enable();
+--------------
+const async_hooks = require('node:async_hooks');
+
+const hook = async_hooks.createHook(callbacks).enable();
+```
+
+#### `asyncHook.disable()`
+
+* Returns: [`AsyncHook`](/api/v16/async_hooks#async_hookscreatehookcallbacks) A reference to `asyncHook`.
+
+Disable the callbacks for a given `AsyncHook` instance from the global pool of
+`AsyncHook` callbacks to be executed. Once a hook has been disabled it will not
+be called again until enabled.
+
+For API consistency `disable()` also returns the `AsyncHook` instance.
+
+#### Hook callbacks
+
+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.
+
+##### `init(asyncId, type, triggerAsyncId, resource)`
+
+* `asyncId` [`number`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type) A unique ID for the async resource.
+* `type` [`string`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type) The type of the async resource.
+* `triggerAsyncId` [`number`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type) The unique ID of the async resource in whose
+ execution context this async resource was created.
+* `resource` [`Object`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object) Reference to the resource representing the async
+ operation, needs to be released during _destroy_.
+
+Called when a class is constructed that has the _possibility_ to emit an
+asynchronous event. This _does not_ mean the instance must call
+`before`/`after` before `destroy` is called, only that the possibility
+exists.
+
+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.
+
+```mjs|cjs
+import { createServer } from 'node:net';
+
+createServer().listen(function() { this.close(); });
+// OR
+clearTimeout(setTimeout(() => {}, 10));
+--------------
+require('node:net').createServer().listen(function() { this.close(); });
+// OR
+clearTimeout(setTimeout(() => {}, 10));
+```
+
+Every new resource is assigned an ID that is unique within the scope of the
+current Node.js instance.
+
+###### `type`
+
+The `type` is a string identifying the type of resource that caused
+`init` to be called. Generally, it will correspond to the name of the
+resource's constructor.
+
+Valid values are:
+
+```text
+FSEVENTWRAP, FSREQCALLBACK, GETADDRINFOREQWRAP, GETNAMEINFOREQWRAP, HTTPINCOMINGMESSAGE,
+HTTPCLIENTREQUEST, JSSTREAM, PIPECONNECTWRAP, PIPEWRAP, PROCESSWRAP, QUERYWRAP,
+SHUTDOWNWRAP, SIGNALWRAP, STATWATCHER, TCPCONNECTWRAP, TCPSERVERWRAP, TCPWRAP,
+TTYWRAP, UDPSENDWRAP, UDPWRAP, WRITEWRAP, ZLIB, SSLCONNECTION, PBKDF2REQUEST,
+RANDOMBYTESREQUEST, TLSWRAP, Microtask, Timeout, Immediate, TickObject
+```
+
+These values can change in any Node.js release. Furthermore users of [`AsyncResource`][]
+likely provide other values.
+
+There is also the `PROMISE` resource type, which is used to track `Promise`
+instances and asynchronous work scheduled by them.
+
+Users are able to define their own `type` when using the public embedder API.
+
+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.
+
+###### `triggerAsyncId`
+
+`triggerAsyncId` is the `asyncId` of the resource that caused (or "triggered")
+the new resource to initialize and that caused `init` to call. This is different
+from `async_hooks.executionAsyncId()` that only shows _when_ a resource was
+created, while `triggerAsyncId` shows _why_ a resource was created.
+
+The following is a simple demonstration of `triggerAsyncId`:
+
+```mjs|cjs
+import { createHook, executionAsyncId } from 'node:async_hooks';
+import { stdout } from 'node:process';
+import net from 'node:net';
+
+createHook({
+ init(asyncId, type, triggerAsyncId) {
+ const eid = executionAsyncId();
+ fs.writeSync(
+ stdout.fd,
+ `${type}(${asyncId}): trigger: ${triggerAsyncId} execution: ${eid}\n`);
+ }
+}).enable();
+
+net.createServer((conn) => {}).listen(8080);
+--------------
+const { createHook, executionAsyncId } = require('node:async_hooks');
+const { stdout } = require('node:process');
+const net = require('node:net');
+
+createHook({
+ init(asyncId, type, triggerAsyncId) {
+ const eid = executionAsyncId();
+ fs.writeSync(
+ stdout.fd,
+ `${type}(${asyncId}): trigger: ${triggerAsyncId} execution: ${eid}\n`);
+ }
+}).enable();
+
+net.createServer((conn) => {}).listen(8080);
+```
+
+Output when hitting the server with `nc localhost 8080`:
+
+```console
+TCPSERVERWRAP(5): trigger: 1 execution: 1
+TCPWRAP(7): trigger: 5 execution: 0
+```
+
+The `TCPSERVERWRAP` is the server which receives the connections.
+
+The `TCPWRAP` is the new connection from the client. When a new
+connection is made, the `TCPWrap` instance is immediately constructed. This
+happens outside of any JavaScript stack. (An `executionAsyncId()` of `0` 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 `triggerAsyncId` is given the task
+of propagating what resource is responsible for the new resource's existence.
+
+###### `resource`
+
+`resource` is an object that represents the actual async resource that has
+been initialized. This can contain useful information that can vary based on
+the value of `type`. For instance, for the `GETADDRINFOREQWRAP` resource type,
+`resource` provides the host name used when looking up the IP address for the
+host in `net.Server.listen()`. The API for accessing this information is
+not supported, but using the Embedder API, users can provide
+and document their own resource objects. For example, such a resource object
+could contain the SQL query being executed.
+
+In some cases the resource object is reused for performance reasons, it is
+thus not safe to use it as a key in a `WeakMap` or add properties to it.
+
+###### Asynchronous context example
+
+The following is an example with additional information about the calls to
+`init` between the `before` and `after` calls, specifically what the
+callback to `listen()` will look like. The output formatting is slightly more
+elaborate to make calling context easier to see.
+
+```js
+const async_hooks = require('node:async_hooks');
+const fs = require('node:fs');
+const net = require('node:net');
+const { fd } = process.stdout;
+
+let indent = 0;
+async_hooks.createHook({
+ init(asyncId, type, triggerAsyncId) {
+ const eid = async_hooks.executionAsyncId();
+ const indentStr = ' '.repeat(indent);
+ fs.writeSync(
+ fd,
+ `${indentStr}${type}(${asyncId}):` +
+ ` trigger: ${triggerAsyncId} execution: ${eid}\n`);
+ },
+ before(asyncId) {
+ const indentStr = ' '.repeat(indent);
+ fs.writeSync(fd, `${indentStr}before: ${asyncId}\n`);
+ indent += 2;
+ },
+ after(asyncId) {
+ indent -= 2;
+ const indentStr = ' '.repeat(indent);
+ fs.writeSync(fd, `${indentStr}after: ${asyncId}\n`);
+ },
+ destroy(asyncId) {
+ const indentStr = ' '.repeat(indent);
+ fs.writeSync(fd, `${indentStr}destroy: ${asyncId}\n`);
+ },
+}).enable();
+
+net.createServer(() => {}).listen(8080, () => {
+ // Let's wait 10ms before logging the server started.
+ setTimeout(() => {
+ console.log('>>>', async_hooks.executionAsyncId());
+ }, 10);
+});
+```
+
+Output from only starting the server:
+
+```console
+TCPSERVERWRAP(5): trigger: 1 execution: 1
+TickObject(6): trigger: 5 execution: 1
+before: 6
+ Timeout(7): trigger: 6 execution: 6
+after: 6
+destroy: 6
+before: 7
+>>> 7
+ TickObject(8): trigger: 7 execution: 7
+after: 7
+before: 8
+after: 8
+```
+
+As illustrated in the example, `executionAsyncId()` and `execution` each specify
+the value of the current execution context; which is delineated by calls to
+`before` and `after`.
+
+Only using `execution` to graph resource allocation results in the following:
+
+```console
+ root(1)
+ ^
+ |
+TickObject(6)
+ ^
+ |
+ Timeout(7)
+```
+
+The `TCPSERVERWRAP` is not part of this graph, even though it was the reason for
+`console.log()` being called. This is because binding to a port without a host
+name is a _synchronous_ operation, but to maintain a completely asynchronous
+API the user's callback is placed in a `process.nextTick()`. Which is why
+`TickObject` is present in the output and is a 'parent' for `.listen()`
+callback.
+
+The graph only shows _when_ a resource was created, not _why_, so to track
+the _why_ use `triggerAsyncId`. Which can be represented with the following
+graph:
+
+```console
+ bootstrap(1)
+ |
+ ˅
+TCPSERVERWRAP(5)
+ |
+ ˅
+ TickObject(6)
+ |
+ ˅
+ Timeout(7)
+```
+
+##### `before(asyncId)`
+
+* `asyncId` [`number`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type)
+
+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 `before` callback is called just before said
+callback is executed. `asyncId` is the unique identifier assigned to the
+resource about to execute the callback.
+
+The `before` callback will be called 0 to N times. The `before` 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 `before`
+callback multiple times, while other operations like `fs.open()` will call
+it only once.
+
+##### `after(asyncId)`
+
+* `asyncId` [`number`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type)
+
+Called immediately after the callback specified in `before` is completed.
+
+If an uncaught exception occurs during execution of the callback, then `after`
+will run _after_ the `'uncaughtException'` event is emitted or a `domain`'s
+handler runs.
+
+##### `destroy(asyncId)`
+
+* `asyncId` [`number`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type)
+
+Called after the resource corresponding to `asyncId` is destroyed. It is also
+called asynchronously from the embedder API `emitDestroy()`.
+
+Some resources depend on garbage collection for cleanup, so if a reference is
+made to the `resource` object passed to `init` it is possible that `destroy`
+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.
+
+##### `promiseResolve(asyncId)`
+
+
+
+* `asyncId` [`number`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type)
+
+Called when the `resolve` function passed to the `Promise` constructor is
+invoked (either directly or through other means of resolving a promise).
+
+`resolve()` does not do any observable synchronous work.
+
+The `Promise` is not necessarily fulfilled or rejected at this point if the
+`Promise` was resolved by assuming the state of another `Promise`.
+
+```js
+new Promise((resolve) => resolve(true)).then((a) => {});
+```
+
+calls the following callbacks:
+
+```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
+```
+
+#### `async_hooks.executionAsyncResource()`
+
+
+
+* Returns: [`Object`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object) The resource representing the current execution.
+ Useful to store data within the resource.
+
+Resource objects returned by `executionAsyncResource()` 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.
+
+Using `executionAsyncResource()` 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.
+
+```mjs|cjs
+import { open } from 'node:fs';
+import { executionAsyncId, executionAsyncResource } from 'node:async_hooks';
+
+console.log(executionAsyncId(), executionAsyncResource()); // 1 {}
+open(new URL(import.meta.url), 'r', (err, fd) => {
+ console.log(executionAsyncId(), executionAsyncResource()); // 7 FSReqWrap
+});
+--------------
+const { open } = require('node:fs');
+const { executionAsyncId, executionAsyncResource } = require('node:async_hooks');
+
+console.log(executionAsyncId(), executionAsyncResource()); // 1 {}
+open(__filename, 'r', (err, fd) => {
+ console.log(executionAsyncId(), executionAsyncResource()); // 7 FSReqWrap
+});
+```
+
+This can be used to implement continuation local storage without the
+use of a tracking `Map` to store the metadata:
+
+```mjs|cjs
+import { createServer } from 'node:http';
+import {
+ executionAsyncId,
+ executionAsyncResource,
+ createHook
+} from 'async_hooks';
+const sym = Symbol('state'); // Private symbol to avoid pollution
+
+createHook({
+ init(asyncId, type, triggerAsyncId, resource) {
+ const cr = executionAsyncResource();
+ if (cr) {
+ resource[sym] = cr[sym];
+ }
+ }
+}).enable();
+
+const server = createServer((req, res) => {
+ executionAsyncResource()[sym] = { state: req.url };
+ setTimeout(function() {
+ res.end(JSON.stringify(executionAsyncResource()[sym]));
+ }, 100);
+}).listen(3000);
+--------------
+const { createServer } = require('node:http');
+const {
+ executionAsyncId,
+ executionAsyncResource,
+ createHook
+} = require('node:async_hooks');
+const sym = Symbol('state'); // Private symbol to avoid pollution
+
+createHook({
+ init(asyncId, type, triggerAsyncId, resource) {
+ const cr = executionAsyncResource();
+ if (cr) {
+ resource[sym] = cr[sym];
+ }
+ }
+}).enable();
+
+const server = createServer((req, res) => {
+ executionAsyncResource()[sym] = { state: req.url };
+ setTimeout(function() {
+ res.end(JSON.stringify(executionAsyncResource()[sym]));
+ }, 100);
+}).listen(3000);
+```
+
+#### `async_hooks.executionAsyncId()`
+
+
+
+* Returns: [`number`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type) The `asyncId` of the current execution context. Useful to
+ track when something calls.
+
+```mjs|cjs
+import { executionAsyncId } from 'node:async_hooks';
+
+console.log(executionAsyncId()); // 1 - bootstrap
+fs.open(path, 'r', (err, fd) => {
+ console.log(executionAsyncId()); // 6 - open()
+});
+--------------
+const async_hooks = require('node:async_hooks');
+
+console.log(async_hooks.executionAsyncId()); // 1 - bootstrap
+fs.open(path, 'r', (err, fd) => {
+ console.log(async_hooks.executionAsyncId()); // 6 - open()
+});
+```
+
+The ID returned from `executionAsyncId()` is related to execution timing, not
+causality (which is covered by `triggerAsyncId()`):
+
+```js
+const server = net.createServer((conn) => {
+ // Returns the ID of the server, not of the new connection, because the
+ // callback runs in the execution scope of the server's MakeCallback().
+ async_hooks.executionAsyncId();
+
+}).listen(port, () => {
+ // Returns the ID of a TickObject (process.nextTick()) because all
+ // callbacks passed to .listen() are wrapped in a nextTick().
+ async_hooks.executionAsyncId();
+});
+```
+
+Promise contexts may not get precise `executionAsyncIds` by default.
+See the section on [promise execution tracking][].
+
+#### `async_hooks.triggerAsyncId()`
+
+* Returns: [`number`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type) The ID of the resource responsible for calling the callback
+ that is currently being executed.
+
+```js
+const server = net.createServer((conn) => {
+ // The resource that caused (or triggered) this callback to be called
+ // was that of the new connection. Thus the return value of triggerAsyncId()
+ // is the asyncId of "conn".
+ async_hooks.triggerAsyncId();
+
+}).listen(port, () => {
+ // Even though all callbacks passed to .listen() are wrapped in a nextTick()
+ // the callback itself exists because the call to the server's .listen()
+ // was made. So the return value would be the ID of the server.
+ async_hooks.triggerAsyncId();
+});
+```
+
+Promise contexts may not get valid `triggerAsyncId`s by default. See
+the section on [promise execution tracking][].
+
+#### `async_hooks.asyncWrapProviders`
+
+
+
+* Returns: A map of provider types to the corresponding numeric id.
+ This map contains all the event types that might be emitted by the `async_hooks.init()` event.
+
+This feature suppresses the deprecated usage of `process.binding('async_wrap').Providers`.
+See: [DEP0111][]
+
+### Promise execution tracking
+
+By default, promise executions are not assigned `asyncId`s due to the relatively
+expensive nature of the [promise introspection API][PromiseHooks] provided by
+V8. This means that programs using promises or `async`/`await` will not get
+correct execution and trigger ids for promise callback contexts by default.
+
+```mjs|cjs
+import { executionAsyncId, triggerAsyncId } from 'node:async_hooks';
+
+Promise.resolve(1729).then(() => {
+ console.log(`eid ${executionAsyncId()} tid ${triggerAsyncId()}`);
+});
+// produces:
+// eid 1 tid 0
+--------------
+const { executionAsyncId, triggerAsyncId } = require('node:async_hooks');
+
+Promise.resolve(1729).then(() => {
+ console.log(`eid ${executionAsyncId()} tid ${triggerAsyncId()}`);
+});
+// produces:
+// eid 1 tid 0
+```
+
+Observe that the `then()` callback claims to have executed in the context of the
+outer scope even though there was an asynchronous hop involved. Also,
+the `triggerAsyncId` value is `0`, which means that we are missing context about
+the resource that caused (triggered) the `then()` callback to be executed.
+
+Installing async hooks via `async_hooks.createHook` enables promise execution
+tracking:
+
+```mjs|cjs
+import { createHook, executionAsyncId, triggerAsyncId } from 'node:async_hooks';
+createHook({ init() {} }).enable(); // forces PromiseHooks to be enabled.
+Promise.resolve(1729).then(() => {
+ console.log(`eid ${executionAsyncId()} tid ${triggerAsyncId()}`);
+});
+// produces:
+// eid 7 tid 6
+--------------
+const { createHook, executionAsyncId, triggerAsyncId } = require('node:async_hooks');
+
+createHook({ init() {} }).enable(); // forces PromiseHooks to be enabled.
+Promise.resolve(1729).then(() => {
+ console.log(`eid ${executionAsyncId()} tid ${triggerAsyncId()}`);
+});
+// produces:
+// eid 7 tid 6
+```
+
+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
+`Promise.resolve()` and the promise returned by the call to `then()`. In the
+example above, the first promise got the `asyncId` `6` and the latter got
+`asyncId` `7`. During the execution of the `then()` callback, we are executing
+in the context of promise with `asyncId` `7`. This promise was triggered by
+async resource `6`.
+
+Another subtlety with promises is that `before` and `after` callbacks are run
+only on chained promises. That means promises not created by `then()`/`catch()`
+will not have the `before` and `after` callbacks fired on them. For more details
+see the details of the V8 [PromiseHooks][] API.
+
+### JavaScript embedder API
+
+Library developers that handle their own asynchronous resources performing tasks
+like I/O, connection pooling, or managing callback queues may use the
+`AsyncResource` JavaScript API so that all the appropriate callbacks are called.
+
+#### `AsyncResource`
+
+The documentation for this class has moved [`AsyncResource`][].
+
+### `AsyncLocalStorage`
+
+The documentation for this class has moved [`AsyncLocalStorage`][].
+
+[DEP0111]: /api/v16/deprecations#dep0111-processbinding
+[Hook Callbacks]: #hook-callbacks
+[PromiseHooks]: https://docs.google.com/document/d/1rda3yKGHimKIhg5YeoAmCOtyURgsbTH_qaYR79FELlk/edit
+[`AsyncLocalStorage`]: async_context.md#class-asynclocalstorage
+[`AsyncResource`]: async_context.md#class-asyncresource
+[`Worker`]: worker_threads.md#class-worker
+[`after` callback]: #afterasyncid
+[`before` callback]: #beforeasyncid
+[`destroy` callback]: #destroyasyncid
+[`init` callback]: #initasyncid-type-triggerasyncid-resource
+[`promiseResolve` callback]: #promiseresolveasyncid
+[promise execution tracking]: #promise-execution-tracking
diff --git a/content/api/v16/buffer.en.md b/content/api/v16/buffer.en.md
new file mode 100644
index 0000000000..c00e1ae2f2
--- /dev/null
+++ b/content/api/v16/buffer.en.md
@@ -0,0 +1,4519 @@
+---
+title: 'buffer'
+displayTitle: 'Buffer'
+category: 'api'
+version: 'v16'
+---
+
+
+
+
+
+Stable
+
+
+
+
+
+`Buffer` objects are used to represent a fixed-length sequence of bytes. Many
+Node.js APIs support `Buffer`s.
+
+The `Buffer` class is a subclass of JavaScript's [`Uint8Array`][] class and
+extends it with methods that cover additional use cases. Node.js APIs accept
+plain [`Uint8Array`][]s wherever `Buffer`s are supported as well.
+
+While the `Buffer` class is available within the global scope, it is still
+recommended to explicitly reference it via an import or require statement.
+
+```mjs|cjs
+import { Buffer } from 'node:buffer';
+
+// Creates a zero-filled Buffer of length 10.
+const buf1 = Buffer.alloc(10);
+
+// Creates a Buffer of length 10,
+// filled with bytes which all have the value `1`.
+const buf2 = Buffer.alloc(10, 1);
+
+// Creates an uninitialized buffer of length 10.
+// This is faster than calling Buffer.alloc() but the returned
+// Buffer instance might contain old data that needs to be
+// overwritten using fill(), write(), or other functions that fill the Buffer's
+// contents.
+const buf3 = Buffer.allocUnsafe(10);
+
+// Creates a Buffer containing the bytes [1, 2, 3].
+const buf4 = Buffer.from([1, 2, 3]);
+
+// Creates a Buffer containing the bytes [1, 1, 1, 1] – the entries
+// are all truncated using `(value & 255)` to fit into the range 0–255.
+const buf5 = Buffer.from([257, 257.5, -255, '1']);
+
+// Creates a Buffer containing the UTF-8-encoded bytes for the string 'tést':
+// [0x74, 0xc3, 0xa9, 0x73, 0x74] (in hexadecimal notation)
+// [116, 195, 169, 115, 116] (in decimal notation)
+const buf6 = Buffer.from('tést');
+
+// Creates a Buffer containing the Latin-1 bytes [0x74, 0xe9, 0x73, 0x74].
+const buf7 = Buffer.from('tést', 'latin1');
+--------------
+const { Buffer } = require('node:buffer');
+
+// Creates a zero-filled Buffer of length 10.
+const buf1 = Buffer.alloc(10);
+
+// Creates a Buffer of length 10,
+// filled with bytes which all have the value `1`.
+const buf2 = Buffer.alloc(10, 1);
+
+// Creates an uninitialized buffer of length 10.
+// This is faster than calling Buffer.alloc() but the returned
+// Buffer instance might contain old data that needs to be
+// overwritten using fill(), write(), or other functions that fill the Buffer's
+// contents.
+const buf3 = Buffer.allocUnsafe(10);
+
+// Creates a Buffer containing the bytes [1, 2, 3].
+const buf4 = Buffer.from([1, 2, 3]);
+
+// Creates a Buffer containing the bytes [1, 1, 1, 1] – the entries
+// are all truncated using `(value & 255)` to fit into the range 0–255.
+const buf5 = Buffer.from([257, 257.5, -255, '1']);
+
+// Creates a Buffer containing the UTF-8-encoded bytes for the string 'tést':
+// [0x74, 0xc3, 0xa9, 0x73, 0x74] (in hexadecimal notation)
+// [116, 195, 169, 115, 116] (in decimal notation)
+const buf6 = Buffer.from('tést');
+
+// Creates a Buffer containing the Latin-1 bytes [0x74, 0xe9, 0x73, 0x74].
+const buf7 = Buffer.from('tést', 'latin1');
+```
+
+### Buffers and character encodings
+
+
+
+When converting between `Buffer`s and strings, a character encoding may be
+specified. If no character encoding is specified, UTF-8 will be used as the
+default.
+
+```mjs|cjs
+import { Buffer } from 'node:buffer';
+
+const buf = Buffer.from('hello world', 'utf8');
+
+console.log(buf.toString('hex'));
+// Prints: 68656c6c6f20776f726c64
+console.log(buf.toString('base64'));
+// Prints: aGVsbG8gd29ybGQ=
+
+console.log(Buffer.from('fhqwhgads', 'utf8'));
+// Prints:
+console.log(Buffer.from('fhqwhgads', 'utf16le'));
+// Prints:
+--------------
+const { Buffer } = require('node:buffer');
+
+const buf = Buffer.from('hello world', 'utf8');
+
+console.log(buf.toString('hex'));
+// Prints: 68656c6c6f20776f726c64
+console.log(buf.toString('base64'));
+// Prints: aGVsbG8gd29ybGQ=
+
+console.log(Buffer.from('fhqwhgads', 'utf8'));
+// Prints:
+console.log(Buffer.from('fhqwhgads', 'utf16le'));
+// Prints:
+```
+
+Node.js buffers accept all case variations of encoding strings that they
+receive. For example, UTF-8 can be specified as `'utf8'`, `'UTF8'`, or `'uTf8'`.
+
+The character encodings currently supported by Node.js are the following:
+
+* `'utf8'` (alias: `'utf-8'`): Multi-byte encoded Unicode characters. Many web
+ pages and other document formats use [UTF-8][]. This is the default character
+ encoding. When decoding a `Buffer` into a string that does not exclusively
+ contain valid UTF-8 data, the Unicode replacement character `U+FFFD` � will be
+ used to represent those errors.
+
+* `'utf16le'` (alias: `'utf-16le'`): Multi-byte encoded Unicode characters.
+ Unlike `'utf8'`, each character in the string will be encoded using either 2
+ or 4 bytes. Node.js only supports the [little-endian][endianness] variant of
+ [UTF-16][].
+
+* `'latin1'`: Latin-1 stands for [ISO-8859-1][]. This character encoding only
+ supports the Unicode characters from `U+0000` to `U+00FF`. 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.
+
+Converting a `Buffer` into a string using one of the above is referred to as
+decoding, and converting a string into a `Buffer` is referred to as encoding.
+
+Node.js also supports the following binary-to-text encodings. For
+binary-to-text encodings, the naming convention is reversed: Converting a
+`Buffer` into a string is typically referred to as encoding, and converting a
+string into a `Buffer` as decoding.
+
+* `'base64'`: [Base64][] encoding. When creating a `Buffer` from a string,
+ this encoding will also correctly accept "URL and Filename Safe Alphabet" as
+ specified in [RFC 4648, Section 5][]. Whitespace characters such as spaces,
+ tabs, and new lines contained within the base64-encoded string are ignored.
+
+* `'base64url'`: [base64url][] encoding as specified in
+ [RFC 4648, Section 5][]. When creating a `Buffer` from a string, this
+ encoding will also correctly accept regular base64-encoded strings. When
+ encoding a `Buffer` to a string, this encoding will omit padding.
+
+* `'hex'`: 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.
+
+The following legacy character encodings are also supported:
+
+* `'ascii'`: For 7-bit [ASCII][] data only. When encoding a string into a
+ `Buffer`, this is equivalent to using `'latin1'`. When decoding a `Buffer`
+ into a string, using this encoding will additionally unset the highest bit of
+ each byte before decoding as `'latin1'`.
+ Generally, there should be no reason to use this encoding, as `'utf8'`
+ (or, if the data is known to always be ASCII-only, `'latin1'`) will be a
+ better choice when encoding or decoding ASCII-only text. It is only provided
+ for legacy compatibility.
+
+* `'binary'`: Alias for `'latin1'`. See [binary strings][] for more background
+ on this topic. The name of this encoding can be very misleading, as all of the
+ encodings listed here convert between strings and binary data. For converting
+ between strings and `Buffer`s, typically `'utf8'` is the right choice.
+
+* `'ucs2'`, `'ucs-2'`: Aliases of `'utf16le'`. 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.
+
+```mjs|cjs
+import { Buffer } from 'node:buffer';
+
+Buffer.from('1ag123', 'hex');
+// Prints , data truncated when first non-hexadecimal value
+// ('g') encountered.
+
+Buffer.from('1a7', 'hex');
+// Prints , data truncated when data ends in single digit ('7').
+
+Buffer.from('1634', 'hex');
+// Prints , all data represented.
+--------------
+const { Buffer } = require('node:buffer');
+
+Buffer.from('1ag123', 'hex');
+// Prints , data truncated when first non-hexadecimal value
+// ('g') encountered.
+
+Buffer.from('1a7', 'hex');
+// Prints , data truncated when data ends in single digit ('7').
+
+Buffer.from('1634', 'hex');
+// Prints , all data represented.
+```
+
+Modern Web browsers follow the [WHATWG Encoding Standard][] which aliases
+both `'latin1'` and `'ISO-8859-1'` to `'win-1252'`. This means that while doing
+something like `http.get()`, if the returned charset is one of those listed in
+the WHATWG specification it is possible that the server actually returned
+`'win-1252'`-encoded data, and using `'latin1'` encoding may incorrectly decode
+the characters.
+
+### Buffers and TypedArrays
+
+
+
+`Buffer` instances are also JavaScript [`Uint8Array`][] and [`TypedArray`][]
+instances. All [`TypedArray`][] methods are available on `Buffer`s. There are,
+however, subtle incompatibilities between the `Buffer` API and the
+[`TypedArray`][] API.
+
+In particular:
+
+* While [`TypedArray.prototype.slice()`][] creates a copy of part of the `TypedArray`,
+ [`Buffer.prototype.slice()`][`buf.slice()`] creates a view over the existing `Buffer`
+ without copying. This behavior can be surprising, and only exists for legacy
+ compatibility. [`TypedArray.prototype.subarray()`][] can be used to achieve
+ the behavior of [`Buffer.prototype.slice()`][`buf.slice()`] on both `Buffer`s
+ and other `TypedArray`s and should be preferred.
+* [`buf.toString()`][] is incompatible with its `TypedArray` equivalent.
+* A number of methods, e.g. [`buf.indexOf()`][], support additional arguments.
+
+There are two ways to create new [`TypedArray`][] instances from a `Buffer`:
+
+* Passing a `Buffer` to a [`TypedArray`][] constructor will copy the `Buffer`s
+ contents, interpreted as an array of integers, and not as a byte sequence
+ of the target type.
+
+```mjs|cjs
+import { Buffer } from 'node:buffer';
+
+const buf = Buffer.from([1, 2, 3, 4]);
+const uint32array = new Uint32Array(buf);
+
+console.log(uint32array);
+
+// Prints: Uint32Array(4) [ 1, 2, 3, 4 ]
+--------------
+const { Buffer } = require('node:buffer');
+
+const buf = Buffer.from([1, 2, 3, 4]);
+const uint32array = new Uint32Array(buf);
+
+console.log(uint32array);
+
+// Prints: Uint32Array(4) [ 1, 2, 3, 4 ]
+```
+
+* Passing the `Buffer`s underlying [`ArrayBuffer`][] will create a
+ [`TypedArray`][] that shares its memory with the `Buffer`.
+
+```mjs|cjs
+import { Buffer } from 'node:buffer';
+
+const buf = Buffer.from('hello', 'utf16le');
+const uint16array = new Uint16Array(
+ buf.buffer,
+ buf.byteOffset,
+ buf.length / Uint16Array.BYTES_PER_ELEMENT);
+
+console.log(uint16array);
+
+// Prints: Uint16Array(5) [ 104, 101, 108, 108, 111 ]
+--------------
+const { Buffer } = require('node:buffer');
+
+const buf = Buffer.from('hello', 'utf16le');
+const uint16array = new Uint16Array(
+ buf.buffer,
+ buf.byteOffset,
+ buf.length / Uint16Array.BYTES_PER_ELEMENT);
+
+console.log(uint16array);
+
+// Prints: Uint16Array(5) [ 104, 101, 108, 108, 111 ]
+```
+
+It is possible to create a new `Buffer` that shares the same allocated
+memory as a [`TypedArray`][] instance by using the `TypedArray` object's
+`.buffer` property in the same way. [`Buffer.from()`][`Buffer.from(arrayBuf)`]
+behaves like `new Uint8Array()` in this context.
+
+```mjs|cjs
+import { Buffer } from 'node:buffer';
+
+const arr = new Uint16Array(2);
+
+arr[0] = 5000;
+arr[1] = 4000;
+
+// Copies the contents of `arr`.
+const buf1 = Buffer.from(arr);
+
+// Shares memory with `arr`.
+const buf2 = Buffer.from(arr.buffer);
+
+console.log(buf1);
+// Prints:
+console.log(buf2);
+// Prints:
+
+arr[1] = 6000;
+
+console.log(buf1);
+// Prints:
+console.log(buf2);
+// Prints:
+--------------
+const { Buffer } = require('node:buffer');
+
+const arr = new Uint16Array(2);
+
+arr[0] = 5000;
+arr[1] = 4000;
+
+// Copies the contents of `arr`.
+const buf1 = Buffer.from(arr);
+
+// Shares memory with `arr`.
+const buf2 = Buffer.from(arr.buffer);
+
+console.log(buf1);
+// Prints:
+console.log(buf2);
+// Prints:
+
+arr[1] = 6000;
+
+console.log(buf1);
+// Prints:
+console.log(buf2);
+// Prints:
+```
+
+When creating a `Buffer` using a [`TypedArray`][]'s `.buffer`, it is
+possible to use only a portion of the underlying [`ArrayBuffer`][] by passing in
+`byteOffset` and `length` parameters.
+
+```mjs|cjs
+import { Buffer } from 'node:buffer';
+
+const arr = new Uint16Array(20);
+const buf = Buffer.from(arr.buffer, 0, 16);
+
+console.log(buf.length);
+// Prints: 16
+--------------
+const { Buffer } = require('node:buffer');
+
+const arr = new Uint16Array(20);
+const buf = Buffer.from(arr.buffer, 0, 16);
+
+console.log(buf.length);
+// Prints: 16
+```
+
+The `Buffer.from()` and [`TypedArray.from()`][] have different signatures and
+implementations. Specifically, the [`TypedArray`][] variants accept a second
+argument that is a mapping function that is invoked on every element of the
+typed array:
+
+* `TypedArray.from(source[, mapFn[, thisArg]])`
+
+The `Buffer.from()` method, however, does not support the use of a mapping
+function:
+
+* [`Buffer.from(array)`][]
+* [`Buffer.from(buffer)`][]
+* [`Buffer.from(arrayBuffer[, byteOffset[, length]])`][`Buffer.from(arrayBuf)`]
+* [`Buffer.from(string[, encoding])`][`Buffer.from(string)`]
+
+### Buffers and iteration
+
+`Buffer` instances can be iterated over using `for..of` syntax:
+
+```mjs|cjs
+import { Buffer } from 'node:buffer';
+
+const buf = Buffer.from([1, 2, 3]);
+
+for (const b of buf) {
+ console.log(b);
+}
+// Prints:
+// 1
+// 2
+// 3
+--------------
+const { Buffer } = require('node:buffer');
+
+const buf = Buffer.from([1, 2, 3]);
+
+for (const b of buf) {
+ console.log(b);
+}
+// Prints:
+// 1
+// 2
+// 3
+```
+
+Additionally, the [`buf.values()`][], [`buf.keys()`][], and
+[`buf.entries()`][] methods can be used to create iterators.
+
+### `Blob`
+
+
+
+A [`Blob`][] encapsulates immutable, raw data that can be safely shared across
+multiple worker threads.
+
+#### `new buffer.Blob([sources[, options]])`
+
+
+
+* `sources` string\[]|ArrayBuffer\[]|TypedArray\[]|DataView\[]|Blob\[] An
+ array of string, [`ArrayBuffer`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/ArrayBuffer), [`TypedArray`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/TypedArray), [`DataView`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/DataView), or [`Blob`](/api/v16/buffer#blob) objects,
+ or any mix of such objects, that will be stored within the `Blob`.
+* `options` [`Object`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object)
+ * `endings` [`string`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type) One of either `'transparent'` or `'native'`. When set
+ to `'native'`, line endings in string source parts will be converted to
+ the platform native line-ending as specified by `require('node:os').EOL`.
+ * `type` [`string`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type) The Blob content-type. The intent is for `type` to convey
+ the MIME media type of the data, however no validation of the type format
+ is performed.
+
+Creates a new `Blob` object containing a concatenation of the given sources.
+
+[`ArrayBuffer`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/ArrayBuffer), [`TypedArray`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/TypedArray), [`DataView`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/DataView), and [`Buffer`](/api/v16/buffer#buffer) sources are copied into
+the 'Blob' and can therefore be safely modified after the 'Blob' is created.
+
+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.
+
+#### `blob.arrayBuffer()`
+
+
+
+* Returns: [`Promise`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Promise)
+
+Returns a promise that fulfills with an [`ArrayBuffer`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/ArrayBuffer) containing a copy of
+the `Blob` data.
+
+#### `blob.size`
+
+
+
+The total size of the `Blob` in bytes.
+
+#### `blob.slice([start[, end[, type]]])`
+
+
+
+* `start` [`number`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type) The starting index.
+* `end` [`number`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type) The ending index.
+* `type` [`string`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type) The content-type for the new `Blob`
+
+Creates and returns a new `Blob` containing a subset of this `Blob` objects
+data. The original `Blob` is not altered.
+
+#### `blob.stream()`
+
+
+
+* Returns: [`ReadableStream`](/api/v16/webstreams#readablestream)
+
+Returns a new `ReadableStream` that allows the content of the `Blob` to be read.
+
+#### `blob.text()`
+
+
+
+* Returns: [`Promise`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Promise)
+
+Returns a promise that fulfills with the contents of the `Blob` decoded as a
+UTF-8 string.
+
+#### `blob.type`
+
+
+
+* Type: [`string`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type)
+
+The content-type of the `Blob`.
+
+#### `Blob` objects and `MessageChannel`
+
+Once a [`Blob`](/api/v16/buffer#blob) object is created, it can be sent via `MessagePort` to multiple
+destinations without transferring or immediately copying the data. The data
+contained by the `Blob` is copied only when the `arrayBuffer()` or `text()`
+methods are called.
+
+```mjs|cjs
+import { Blob, Buffer } from 'node:buffer';
+import { setTimeout as delay } from 'node:timers/promises';
+
+const blob = new Blob(['hello there']);
+
+const mc1 = new MessageChannel();
+const mc2 = new MessageChannel();
+
+mc1.port1.onmessage = async ({ data }) => {
+ console.log(await data.arrayBuffer());
+ mc1.port1.close();
+};
+
+mc2.port1.onmessage = async ({ data }) => {
+ await delay(1000);
+ console.log(await data.arrayBuffer());
+ mc2.port1.close();
+};
+
+mc1.port2.postMessage(blob);
+mc2.port2.postMessage(blob);
+
+// The Blob is still usable after posting.
+blob.text().then(console.log);
+--------------
+const { Blob, Buffer } = require('node:buffer');
+const { setTimeout: delay } = require('node:timers/promises');
+
+const blob = new Blob(['hello there']);
+
+const mc1 = new MessageChannel();
+const mc2 = new MessageChannel();
+
+mc1.port1.onmessage = async ({ data }) => {
+ console.log(await data.arrayBuffer());
+ mc1.port1.close();
+};
+
+mc2.port1.onmessage = async ({ data }) => {
+ await delay(1000);
+ console.log(await data.arrayBuffer());
+ mc2.port1.close();
+};
+
+mc1.port2.postMessage(blob);
+mc2.port2.postMessage(blob);
+
+// The Blob is still usable after posting.
+blob.text().then(console.log);
+```
+
+### `Buffer`
+
+The `Buffer` class is a global type for dealing with binary data directly.
+It can be constructed in a variety of ways.
+
+#### Static method: `Buffer.alloc(size[, fill[, encoding]])`
+
+
+
+* `size` [`integer`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type) The desired length of the new `Buffer`.
+* `fill` [`string`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type) | [`Buffer`](/api/v16/buffer#buffer) | [`Uint8Array`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Uint8Array) | [`integer`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type) A value to pre-fill the new `Buffer`
+ with. **Default:** `0`.
+* `encoding` [`string`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type) If `fill` is a string, this is its encoding.
+ **Default:** `'utf8'`.
+
+Allocates a new `Buffer` of `size` bytes. If `fill` is `undefined`, the
+`Buffer` will be zero-filled.
+
+```mjs|cjs
+import { Buffer } from 'node:buffer';
+
+const buf = Buffer.alloc(5);
+
+console.log(buf);
+// Prints:
+--------------
+const { Buffer } = require('node:buffer');
+
+const buf = Buffer.alloc(5);
+
+console.log(buf);
+// Prints:
+```
+
+If `size` is larger than
+[`buffer.constants.MAX_LENGTH`][] or smaller than 0, [`ERR_INVALID_ARG_VALUE`][]
+is thrown.
+
+If `fill` is specified, the allocated `Buffer` will be initialized by calling
+[`buf.fill(fill)`][`buf.fill()`].
+
+```mjs|cjs
+import { Buffer } from 'node:buffer';
+
+const buf = Buffer.alloc(5, 'a');
+
+console.log(buf);
+// Prints:
+--------------
+const { Buffer } = require('node:buffer');
+
+const buf = Buffer.alloc(5, 'a');
+
+console.log(buf);
+// Prints:
+```
+
+If both `fill` and `encoding` are specified, the allocated `Buffer` will be
+initialized by calling [`buf.fill(fill, encoding)`][`buf.fill()`].
+
+```mjs|cjs
+import { Buffer } from 'node:buffer';
+
+const buf = Buffer.alloc(11, 'aGVsbG8gd29ybGQ=', 'base64');
+
+console.log(buf);
+// Prints:
+--------------
+const { Buffer } = require('node:buffer');
+
+const buf = Buffer.alloc(11, 'aGVsbG8gd29ybGQ=', 'base64');
+
+console.log(buf);
+// Prints:
+```
+
+Calling [`Buffer.alloc()`][] can be measurably slower than the alternative
+[`Buffer.allocUnsafe()`][] but ensures that the newly created `Buffer` instance
+contents will never contain sensitive data from previous allocations, including
+data that might not have been allocated for `Buffer`s.
+
+A `TypeError` will be thrown if `size` is not a number.
+
+#### Static method: `Buffer.allocUnsafe(size)`
+
+
+
+* `size` [`integer`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type) The desired length of the new `Buffer`.
+
+Allocates a new `Buffer` of `size` bytes. If `size` is larger than
+[`buffer.constants.MAX_LENGTH`][] or smaller than 0, [`ERR_INVALID_ARG_VALUE`][]
+is thrown.
+
+The underlying memory for `Buffer` instances created in this way is _not
+initialized_. The contents of the newly created `Buffer` are unknown and
+_may contain sensitive data_. Use [`Buffer.alloc()`][] instead to initialize
+`Buffer` instances with zeroes.
+
+```mjs|cjs
+import { Buffer } from 'node:buffer';
+
+const buf = Buffer.allocUnsafe(10);
+
+console.log(buf);
+// Prints (contents may vary):
+
+buf.fill(0);
+
+console.log(buf);
+// Prints:
+--------------
+const { Buffer } = require('node:buffer');
+
+const buf = Buffer.allocUnsafe(10);
+
+console.log(buf);
+// Prints (contents may vary):
+
+buf.fill(0);
+
+console.log(buf);
+// Prints:
+```
+
+A `TypeError` will be thrown if `size` is not a number.
+
+The `Buffer` module pre-allocates an internal `Buffer` instance of
+size [`Buffer.poolSize`][] that is used as a pool for the fast allocation of new
+`Buffer` instances created using [`Buffer.allocUnsafe()`][],
+[`Buffer.from(array)`][], [`Buffer.concat()`][], and the deprecated
+`new Buffer(size)` constructor only when `size` is less than or equal
+to `Buffer.poolSize >> 1` (floor of [`Buffer.poolSize`][] divided by two).
+
+Use of this pre-allocated internal memory pool is a key difference between
+calling `Buffer.alloc(size, fill)` vs. `Buffer.allocUnsafe(size).fill(fill)`.
+Specifically, `Buffer.alloc(size, fill)` will _never_ use the internal `Buffer`
+pool, while `Buffer.allocUnsafe(size).fill(fill)` _will_ use the internal
+`Buffer` pool if `size` is less than or equal to half [`Buffer.poolSize`][]. The
+difference is subtle but can be important when an application requires the
+additional performance that [`Buffer.allocUnsafe()`][] provides.
+
+#### Static method: `Buffer.allocUnsafeSlow(size)`
+
+
+
+* `size` [`integer`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type) The desired length of the new `Buffer`.
+
+Allocates a new `Buffer` of `size` bytes. If `size` is larger than
+[`buffer.constants.MAX_LENGTH`][] or smaller than 0, [`ERR_INVALID_ARG_VALUE`][]
+is thrown. A zero-length `Buffer` is created if `size` is 0.
+
+The underlying memory for `Buffer` instances created in this way is _not
+initialized_. The contents of the newly created `Buffer` are unknown and
+_may contain sensitive data_. Use [`buf.fill(0)`][`buf.fill()`] to initialize
+such `Buffer` instances with zeroes.
+
+When using [`Buffer.allocUnsafe()`][] to allocate new `Buffer` instances,
+allocations under 4 KiB are sliced from a single pre-allocated `Buffer`. This
+allows applications to avoid the garbage collection overhead of creating many
+individually allocated `Buffer` instances. This approach improves both
+performance and memory usage by eliminating the need to track and clean up as
+many individual `ArrayBuffer` objects.
+
+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 `Buffer` instance using `Buffer.allocUnsafeSlow()` and
+then copying out the relevant bits.
+
+```mjs|cjs
+import { Buffer } from 'node:buffer';
+
+// Need to keep around a few small chunks of memory.
+const store = [];
+
+socket.on('readable', () => {
+ let data;
+ while (null !== (data = readable.read())) {
+ // Allocate for retained data.
+ const sb = Buffer.allocUnsafeSlow(10);
+
+ // Copy the data into the new allocation.
+ data.copy(sb, 0, 0, 10);
+
+ store.push(sb);
+ }
+});
+--------------
+const { Buffer } = require('node:buffer');
+
+// Need to keep around a few small chunks of memory.
+const store = [];
+
+socket.on('readable', () => {
+ let data;
+ while (null !== (data = readable.read())) {
+ // Allocate for retained data.
+ const sb = Buffer.allocUnsafeSlow(10);
+
+ // Copy the data into the new allocation.
+ data.copy(sb, 0, 0, 10);
+
+ store.push(sb);
+ }
+});
+```
+
+A `TypeError` will be thrown if `size` is not a number.
+
+#### Static method: `Buffer.byteLength(string[, encoding])`
+
+
+
+* `string` [`string`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type) | [`Buffer`](/api/v16/buffer#buffer) | [`TypedArray`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/TypedArray) | [`DataView`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/DataView) | [`ArrayBuffer`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/ArrayBuffer) | [`SharedArrayBuffer`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/SharedArrayBuffer) A
+ value to calculate the length of.
+* `encoding` [`string`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type) If `string` is a string, this is its encoding.
+ **Default:** `'utf8'`.
+* Returns: [`integer`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type) The number of bytes contained within `string`.
+
+Returns the byte length of a string when encoded using `encoding`.
+This is not the same as [`String.prototype.length`][], which does not account
+for the encoding that is used to convert the string into bytes.
+
+For `'base64'`, `'base64url'`, and `'hex'`, 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 `Buffer` created from the
+string.
+
+```mjs|cjs
+import { Buffer } from 'node:buffer';
+
+const str = '\u00bd + \u00bc = \u00be';
+
+console.log(`${str}: ${str.length} characters, ` +
+ `${Buffer.byteLength(str, 'utf8')} bytes`);
+// Prints: ½ + ¼ = ¾: 9 characters, 12 bytes
+--------------
+const { Buffer } = require('node:buffer');
+
+const str = '\u00bd + \u00bc = \u00be';
+
+console.log(`${str}: ${str.length} characters, ` +
+ `${Buffer.byteLength(str, 'utf8')} bytes`);
+// Prints: ½ + ¼ = ¾: 9 characters, 12 bytes
+```
+
+When `string` is a `Buffer`/[`DataView`][]/[`TypedArray`][]/[`ArrayBuffer`][]/
+[`SharedArrayBuffer`][], the byte length as reported by `.byteLength`
+is returned.
+
+#### Static method: `Buffer.compare(buf1, buf2)`
+
+
+
+* `buf1` [`Buffer`](/api/v16/buffer#buffer) | [`Uint8Array`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Uint8Array)
+* `buf2` [`Buffer`](/api/v16/buffer#buffer) | [`Uint8Array`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Uint8Array)
+* Returns: [`integer`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type) Either `-1`, `0`, or `1`, depending on the result of the
+ comparison. See [`buf.compare()`][] for details.
+
+Compares `buf1` to `buf2`, typically for the purpose of sorting arrays of
+`Buffer` instances. This is equivalent to calling
+[`buf1.compare(buf2)`][`buf.compare()`].
+
+```mjs|cjs
+import { Buffer } from 'node:buffer';
+
+const buf1 = Buffer.from('1234');
+const buf2 = Buffer.from('0123');
+const arr = [buf1, buf2];
+
+console.log(arr.sort(Buffer.compare));
+// Prints: [ , ]
+// (This result is equal to: [buf2, buf1].)
+--------------
+const { Buffer } = require('node:buffer');
+
+const buf1 = Buffer.from('1234');
+const buf2 = Buffer.from('0123');
+const arr = [buf1, buf2];
+
+console.log(arr.sort(Buffer.compare));
+// Prints: [ , ]
+// (This result is equal to: [buf2, buf1].)
+```
+
+#### Static method: `Buffer.concat(list[, totalLength])`
+
+
+
+* `list` Buffer\[] | Uint8Array\[] List of `Buffer` or [`Uint8Array`][]
+ instances to concatenate.
+* `totalLength` [`integer`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type) Total length of the `Buffer` instances in `list`
+ when concatenated.
+* Returns: [`Buffer`](/api/v16/buffer#buffer)
+
+Returns a new `Buffer` which is the result of concatenating all the `Buffer`
+instances in the `list` together.
+
+If the list has no items, or if the `totalLength` is 0, then a new zero-length
+`Buffer` is returned.
+
+If `totalLength` is not provided, it is calculated from the `Buffer` instances
+in `list` by adding their lengths.
+
+If `totalLength` is provided, it is coerced to an unsigned integer. If the
+combined length of the `Buffer`s in `list` exceeds `totalLength`, the result is
+truncated to `totalLength`.
+
+```mjs|cjs
+import { Buffer } from 'node:buffer';
+
+// Create a single `Buffer` from a list of three `Buffer` instances.
+
+const buf1 = Buffer.alloc(10);
+const buf2 = Buffer.alloc(14);
+const buf3 = Buffer.alloc(18);
+const totalLength = buf1.length + buf2.length + buf3.length;
+
+console.log(totalLength);
+// Prints: 42
+
+const bufA = Buffer.concat([buf1, buf2, buf3], totalLength);
+
+console.log(bufA);
+// Prints:
+console.log(bufA.length);
+// Prints: 42
+--------------
+const { Buffer } = require('node:buffer');
+
+// Create a single `Buffer` from a list of three `Buffer` instances.
+
+const buf1 = Buffer.alloc(10);
+const buf2 = Buffer.alloc(14);
+const buf3 = Buffer.alloc(18);
+const totalLength = buf1.length + buf2.length + buf3.length;
+
+console.log(totalLength);
+// Prints: 42
+
+const bufA = Buffer.concat([buf1, buf2, buf3], totalLength);
+
+console.log(bufA);
+// Prints:
+console.log(bufA.length);
+// Prints: 42
+```
+
+`Buffer.concat()` may also use the internal `Buffer` pool like
+[`Buffer.allocUnsafe()`][] does.
+
+#### Static method: `Buffer.from(array)`
+
+
+
+* `array` integer\[]
+
+Allocates a new `Buffer` using an `array` of bytes in the range `0` – `255`.
+Array entries outside that range will be truncated to fit into it.
+
+```mjs|cjs
+import { Buffer } from 'node:buffer';
+
+// Creates a new Buffer containing the UTF-8 bytes of the string 'buffer'.
+const buf = Buffer.from([0x62, 0x75, 0x66, 0x66, 0x65, 0x72]);
+--------------
+const { Buffer } = require('node:buffer');
+
+// Creates a new Buffer containing the UTF-8 bytes of the string 'buffer'.
+const buf = Buffer.from([0x62, 0x75, 0x66, 0x66, 0x65, 0x72]);
+```
+
+A `TypeError` will be thrown if `array` is not an `Array` or another type
+appropriate for `Buffer.from()` variants.
+
+`Buffer.from(array)` and [`Buffer.from(string)`][] may also use the internal
+`Buffer` pool like [`Buffer.allocUnsafe()`][] does.
+
+#### Static method: `Buffer.from(arrayBuffer[, byteOffset[, length]])`
+
+
+
+* `arrayBuffer` [`ArrayBuffer`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/ArrayBuffer) | [`SharedArrayBuffer`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/SharedArrayBuffer) An [`ArrayBuffer`][],
+ [`SharedArrayBuffer`][], for example the `.buffer` property of a
+ [`TypedArray`][].
+* `byteOffset` [`integer`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type) Index of first byte to expose. **Default:** `0`.
+* `length` [`integer`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type) Number of bytes to expose.
+ **Default:** `arrayBuffer.byteLength - byteOffset`.
+
+This creates a view of the [`ArrayBuffer`][] without copying the underlying
+memory. For example, when passed a reference to the `.buffer` property of a
+[`TypedArray`][] instance, the newly created `Buffer` will share the same
+allocated memory as the [`TypedArray`][]'s underlying `ArrayBuffer`.
+
+```mjs|cjs
+import { Buffer } from 'node:buffer';
+
+const arr = new Uint16Array(2);
+
+arr[0] = 5000;
+arr[1] = 4000;
+
+// Shares memory with `arr`.
+const buf = Buffer.from(arr.buffer);
+
+console.log(buf);
+// Prints:
+
+// Changing the original Uint16Array changes the Buffer also.
+arr[1] = 6000;
+
+console.log(buf);
+// Prints:
+--------------
+const { Buffer } = require('node:buffer');
+
+const arr = new Uint16Array(2);
+
+arr[0] = 5000;
+arr[1] = 4000;
+
+// Shares memory with `arr`.
+const buf = Buffer.from(arr.buffer);
+
+console.log(buf);
+// Prints:
+
+// Changing the original Uint16Array changes the Buffer also.
+arr[1] = 6000;
+
+console.log(buf);
+// Prints:
+```
+
+The optional `byteOffset` and `length` arguments specify a memory range within
+the `arrayBuffer` that will be shared by the `Buffer`.
+
+```mjs|cjs
+import { Buffer } from 'node:buffer';
+
+const ab = new ArrayBuffer(10);
+const buf = Buffer.from(ab, 0, 2);
+
+console.log(buf.length);
+// Prints: 2
+--------------
+const { Buffer } = require('node:buffer');
+
+const ab = new ArrayBuffer(10);
+const buf = Buffer.from(ab, 0, 2);
+
+console.log(buf.length);
+// Prints: 2
+```
+
+A `TypeError` will be thrown if `arrayBuffer` is not an [`ArrayBuffer`][] or a
+[`SharedArrayBuffer`][] or another type appropriate for `Buffer.from()`
+variants.
+
+It is important to remember that a backing `ArrayBuffer` can cover a range
+of memory that extends beyond the bounds of a `TypedArray` view. A new
+`Buffer` created using the `buffer` property of a `TypedArray` may extend
+beyond the range of the `TypedArray`:
+
+```mjs|cjs
+import { Buffer } from 'node:buffer';
+
+const arrA = Uint8Array.from([0x63, 0x64, 0x65, 0x66]); // 4 elements
+const arrB = new Uint8Array(arrA.buffer, 1, 2); // 2 elements
+console.log(arrA.buffer === arrB.buffer); // true
+
+const buf = Buffer.from(arrB.buffer);
+console.log(buf);
+// Prints:
+--------------
+const { Buffer } = require('node:buffer');
+
+const arrA = Uint8Array.from([0x63, 0x64, 0x65, 0x66]); // 4 elements
+const arrB = new Uint8Array(arrA.buffer, 1, 2); // 2 elements
+console.log(arrA.buffer === arrB.buffer); // true
+
+const buf = Buffer.from(arrB.buffer);
+console.log(buf);
+// Prints:
+```
+
+#### Static method: `Buffer.from(buffer)`
+
+
+
+* `buffer` [`Buffer`](/api/v16/buffer#buffer) | [`Uint8Array`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Uint8Array) An existing `Buffer` or [`Uint8Array`][] from
+ which to copy data.
+
+Copies the passed `buffer` data onto a new `Buffer` instance.
+
+```mjs|cjs
+import { Buffer } from 'node:buffer';
+
+const buf1 = Buffer.from('buffer');
+const buf2 = Buffer.from(buf1);
+
+buf1[0] = 0x61;
+
+console.log(buf1.toString());
+// Prints: auffer
+console.log(buf2.toString());
+// Prints: buffer
+--------------
+const { Buffer } = require('node:buffer');
+
+const buf1 = Buffer.from('buffer');
+const buf2 = Buffer.from(buf1);
+
+buf1[0] = 0x61;
+
+console.log(buf1.toString());
+// Prints: auffer
+console.log(buf2.toString());
+// Prints: buffer
+```
+
+A `TypeError` will be thrown if `buffer` is not a `Buffer` or another type
+appropriate for `Buffer.from()` variants.
+
+#### Static method: `Buffer.from(object[, offsetOrEncoding[, length]])`
+
+
+
+* `object` [`Object`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object) An object supporting `Symbol.toPrimitive` or `valueOf()`.
+* `offsetOrEncoding` [`integer`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type) | [`string`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type) A byte-offset or encoding.
+* `length` [`integer`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type) A length.
+
+For objects whose `valueOf()` function returns a value not strictly equal to
+`object`, returns `Buffer.from(object.valueOf(), offsetOrEncoding, length)`.
+
+```mjs|cjs
+import { Buffer } from 'node:buffer';
+
+const buf = Buffer.from(new String('this is a test'));
+// Prints:
+--------------
+const { Buffer } = require('node:buffer');
+
+const buf = Buffer.from(new String('this is a test'));
+// Prints:
+```
+
+For objects that support `Symbol.toPrimitive`, returns
+`Buffer.from(object[Symbol.toPrimitive]('string'), offsetOrEncoding)`.
+
+```mjs|cjs
+import { Buffer } from 'node:buffer';
+
+class Foo {
+ [Symbol.toPrimitive]() {
+ return 'this is a test';
+ }
+}
+
+const buf = Buffer.from(new Foo(), 'utf8');
+// Prints:
+--------------
+const { Buffer } = require('node:buffer');
+
+class Foo {
+ [Symbol.toPrimitive]() {
+ return 'this is a test';
+ }
+}
+
+const buf = Buffer.from(new Foo(), 'utf8');
+// Prints:
+```
+
+A `TypeError` will be thrown if `object` does not have the mentioned methods or
+is not of another type appropriate for `Buffer.from()` variants.
+
+#### Static method: `Buffer.from(string[, encoding])`
+
+
+
+* `string` [`string`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type) A string to encode.
+* `encoding` [`string`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type) The encoding of `string`. **Default:** `'utf8'`.
+
+Creates a new `Buffer` containing `string`. The `encoding` parameter identifies
+the character encoding to be used when converting `string` into bytes.
+
+```mjs|cjs
+import { Buffer } from 'node:buffer';
+
+const buf1 = Buffer.from('this is a tést');
+const buf2 = Buffer.from('7468697320697320612074c3a97374', 'hex');
+
+console.log(buf1.toString());
+// Prints: this is a tést
+console.log(buf2.toString());
+// Prints: this is a tést
+console.log(buf1.toString('latin1'));
+// Prints: this is a tést
+--------------
+const { Buffer } = require('node:buffer');
+
+const buf1 = Buffer.from('this is a tést');
+const buf2 = Buffer.from('7468697320697320612074c3a97374', 'hex');
+
+console.log(buf1.toString());
+// Prints: this is a tést
+console.log(buf2.toString());
+// Prints: this is a tést
+console.log(buf1.toString('latin1'));
+// Prints: this is a tést
+```
+
+A `TypeError` will be thrown if `string` is not a string or another type
+appropriate for `Buffer.from()` variants.
+
+#### Static method: `Buffer.isBuffer(obj)`
+
+
+
+* `obj` [`Object`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object)
+* Returns: [`boolean`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Boolean_type)
+
+Returns `true` if `obj` is a `Buffer`, `false` otherwise.
+
+```mjs|cjs
+import { Buffer } from 'node:buffer';
+
+Buffer.isBuffer(Buffer.alloc(10)); // true
+Buffer.isBuffer(Buffer.from('foo')); // true
+Buffer.isBuffer('a string'); // false
+Buffer.isBuffer([]); // false
+Buffer.isBuffer(new Uint8Array(1024)); // false
+--------------
+const { Buffer } = require('node:buffer');
+
+Buffer.isBuffer(Buffer.alloc(10)); // true
+Buffer.isBuffer(Buffer.from('foo')); // true
+Buffer.isBuffer('a string'); // false
+Buffer.isBuffer([]); // false
+Buffer.isBuffer(new Uint8Array(1024)); // false
+```
+
+#### Static method: `Buffer.isEncoding(encoding)`
+
+
+
+* `encoding` [`string`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type) A character encoding name to check.
+* Returns: [`boolean`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Boolean_type)
+
+Returns `true` if `encoding` is the name of a supported character encoding,
+or `false` otherwise.
+
+```mjs|cjs
+import { Buffer } from 'node:buffer';
+
+console.log(Buffer.isEncoding('utf8'));
+// Prints: true
+
+console.log(Buffer.isEncoding('hex'));
+// Prints: true
+
+console.log(Buffer.isEncoding('utf/8'));
+// Prints: false
+
+console.log(Buffer.isEncoding(''));
+// Prints: false
+--------------
+const { Buffer } = require('node:buffer');
+
+console.log(Buffer.isEncoding('utf8'));
+// Prints: true
+
+console.log(Buffer.isEncoding('hex'));
+// Prints: true
+
+console.log(Buffer.isEncoding('utf/8'));
+// Prints: false
+
+console.log(Buffer.isEncoding(''));
+// Prints: false
+```
+
+#### Class property: `Buffer.poolSize`
+
+
+
+* [`integer`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type) **Default:** `8192`
+
+This is the size (in bytes) of pre-allocated internal `Buffer` instances used
+for pooling. This value may be modified.
+
+#### `buf[index]`
+
+* `index` [`integer`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type)
+
+The index operator `[index]` can be used to get and set the octet at position
+`index` in `buf`. The values refer to individual bytes, so the legal value
+range is between `0x00` and `0xFF` (hex) or `0` and `255` (decimal).
+
+This operator is inherited from `Uint8Array`, so its behavior on out-of-bounds
+access is the same as `Uint8Array`. In other words, `buf[index]` returns
+`undefined` when `index` is negative or greater or equal to `buf.length`, and
+`buf[index] = value` does not modify the buffer if `index` is negative or
+`>= buf.length`.
+
+```mjs|cjs
+import { Buffer } from 'node:buffer';
+
+// Copy an ASCII string into a `Buffer` one byte at a time.
+// (This only works for ASCII-only strings. In general, one should use
+// `Buffer.from()` to perform this conversion.)
+
+const str = 'Node.js';
+const buf = Buffer.allocUnsafe(str.length);
+
+for (let i = 0; i < str.length; i++) {
+ buf[i] = str.charCodeAt(i);
+}
+
+console.log(buf.toString('utf8'));
+// Prints: Node.js
+--------------
+const { Buffer } = require('node:buffer');
+
+// Copy an ASCII string into a `Buffer` one byte at a time.
+// (This only works for ASCII-only strings. In general, one should use
+// `Buffer.from()` to perform this conversion.)
+
+const str = 'Node.js';
+const buf = Buffer.allocUnsafe(str.length);
+
+for (let i = 0; i < str.length; i++) {
+ buf[i] = str.charCodeAt(i);
+}
+
+console.log(buf.toString('utf8'));
+// Prints: Node.js
+```
+
+#### `buf.buffer`
+
+* [`ArrayBuffer`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/ArrayBuffer) The underlying `ArrayBuffer` object based on which this `Buffer`
+ object is created.
+
+This `ArrayBuffer` is not guaranteed to correspond exactly to the original
+`Buffer`. See the notes on `buf.byteOffset` for details.
+
+```mjs|cjs
+import { Buffer } from 'node:buffer';
+
+const arrayBuffer = new ArrayBuffer(16);
+const buffer = Buffer.from(arrayBuffer);
+
+console.log(buffer.buffer === arrayBuffer);
+// Prints: true
+--------------
+const { Buffer } = require('node:buffer');
+
+const arrayBuffer = new ArrayBuffer(16);
+const buffer = Buffer.from(arrayBuffer);
+
+console.log(buffer.buffer === arrayBuffer);
+// Prints: true
+```
+
+#### `buf.byteOffset`
+
+* [`integer`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type) The `byteOffset` of the `Buffer`s underlying `ArrayBuffer` object.
+
+When setting `byteOffset` in `Buffer.from(ArrayBuffer, byteOffset, length)`,
+or sometimes when allocating a `Buffer` smaller than `Buffer.poolSize`, the
+buffer does not start from a zero offset on the underlying `ArrayBuffer`.
+
+This can cause problems when accessing the underlying `ArrayBuffer` directly
+using `buf.buffer`, as other parts of the `ArrayBuffer` may be unrelated
+to the `Buffer` object itself.
+
+A common issue when creating a `TypedArray` object that shares its memory with
+a `Buffer` is that in this case one needs to specify the `byteOffset` correctly:
+
+```mjs|cjs
+import { Buffer } from 'node:buffer';
+
+// Create a buffer smaller than `Buffer.poolSize`.
+const nodeBuffer = Buffer.from([0, 1, 2, 3, 4, 5, 6, 7, 8, 9]);
+
+// When casting the Node.js Buffer to an Int8Array, use the byteOffset
+// to refer only to the part of `nodeBuffer.buffer` that contains the memory
+// for `nodeBuffer`.
+new Int8Array(nodeBuffer.buffer, nodeBuffer.byteOffset, nodeBuffer.length);
+--------------
+const { Buffer } = require('node:buffer');
+
+// Create a buffer smaller than `Buffer.poolSize`.
+const nodeBuffer = Buffer.from([0, 1, 2, 3, 4, 5, 6, 7, 8, 9]);
+
+// When casting the Node.js Buffer to an Int8Array, use the byteOffset
+// to refer only to the part of `nodeBuffer.buffer` that contains the memory
+// for `nodeBuffer`.
+new Int8Array(nodeBuffer.buffer, nodeBuffer.byteOffset, nodeBuffer.length);
+```
+
+#### `buf.compare(target[, targetStart[, targetEnd[, sourceStart[, sourceEnd]]]])`
+
+
+
+* `target` [`Buffer`](/api/v16/buffer#buffer) | [`Uint8Array`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Uint8Array) A `Buffer` or [`Uint8Array`][] with which to
+ compare `buf`.
+* `targetStart` [`integer`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type) The offset within `target` at which to begin
+ comparison. **Default:** `0`.
+* `targetEnd` [`integer`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type) The offset within `target` at which to end comparison
+ (not inclusive). **Default:** `target.length`.
+* `sourceStart` [`integer`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type) The offset within `buf` at which to begin comparison.
+ **Default:** `0`.
+* `sourceEnd` [`integer`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type) The offset within `buf` at which to end comparison
+ (not inclusive). **Default:** [`buf.length`][].
+* Returns: [`integer`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type)
+
+Compares `buf` with `target` and returns a number indicating whether `buf`
+comes before, after, or is the same as `target` in sort order.
+Comparison is based on the actual sequence of bytes in each `Buffer`.
+
+* `0` is returned if `target` is the same as `buf`
+* `1` is returned if `target` should come _before_ `buf` when sorted.
+* `-1` is returned if `target` should come _after_ `buf` when sorted.
+
+```mjs|cjs
+import { Buffer } from 'node:buffer';
+
+const buf1 = Buffer.from('ABC');
+const buf2 = Buffer.from('BCD');
+const buf3 = Buffer.from('ABCD');
+
+console.log(buf1.compare(buf1));
+// Prints: 0
+console.log(buf1.compare(buf2));
+// Prints: -1
+console.log(buf1.compare(buf3));
+// Prints: -1
+console.log(buf2.compare(buf1));
+// Prints: 1
+console.log(buf2.compare(buf3));
+// Prints: 1
+console.log([buf1, buf2, buf3].sort(Buffer.compare));
+// Prints: [ , , ]
+// (This result is equal to: [buf1, buf3, buf2].)
+--------------
+const { Buffer } = require('node:buffer');
+
+const buf1 = Buffer.from('ABC');
+const buf2 = Buffer.from('BCD');
+const buf3 = Buffer.from('ABCD');
+
+console.log(buf1.compare(buf1));
+// Prints: 0
+console.log(buf1.compare(buf2));
+// Prints: -1
+console.log(buf1.compare(buf3));
+// Prints: -1
+console.log(buf2.compare(buf1));
+// Prints: 1
+console.log(buf2.compare(buf3));
+// Prints: 1
+console.log([buf1, buf2, buf3].sort(Buffer.compare));
+// Prints: [ , , ]
+// (This result is equal to: [buf1, buf3, buf2].)
+```
+
+The optional `targetStart`, `targetEnd`, `sourceStart`, and `sourceEnd`
+arguments can be used to limit the comparison to specific ranges within `target`
+and `buf` respectively.
+
+```mjs|cjs
+import { Buffer } from 'node:buffer';
+
+const buf1 = Buffer.from([1, 2, 3, 4, 5, 6, 7, 8, 9]);
+const buf2 = Buffer.from([5, 6, 7, 8, 9, 1, 2, 3, 4]);
+
+console.log(buf1.compare(buf2, 5, 9, 0, 4));
+// Prints: 0
+console.log(buf1.compare(buf2, 0, 6, 4));
+// Prints: -1
+console.log(buf1.compare(buf2, 5, 6, 5));
+// Prints: 1
+--------------
+const { Buffer } = require('node:buffer');
+
+const buf1 = Buffer.from([1, 2, 3, 4, 5, 6, 7, 8, 9]);
+const buf2 = Buffer.from([5, 6, 7, 8, 9, 1, 2, 3, 4]);
+
+console.log(buf1.compare(buf2, 5, 9, 0, 4));
+// Prints: 0
+console.log(buf1.compare(buf2, 0, 6, 4));
+// Prints: -1
+console.log(buf1.compare(buf2, 5, 6, 5));
+// Prints: 1
+```
+
+[`ERR_OUT_OF_RANGE`][] is thrown if `targetStart < 0`, `sourceStart < 0`,
+`targetEnd > target.byteLength`, or `sourceEnd > source.byteLength`.
+
+#### `buf.copy(target[, targetStart[, sourceStart[, sourceEnd]]])`
+
+
+
+* `target` [`Buffer`](/api/v16/buffer#buffer) | [`Uint8Array`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Uint8Array) A `Buffer` or [`Uint8Array`][] to copy into.
+* `targetStart` [`integer`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type) The offset within `target` at which to begin
+ writing. **Default:** `0`.
+* `sourceStart` [`integer`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type) The offset within `buf` from which to begin copying.
+ **Default:** `0`.
+* `sourceEnd` [`integer`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type) The offset within `buf` at which to stop copying (not
+ inclusive). **Default:** [`buf.length`][].
+* Returns: [`integer`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type) The number of bytes copied.
+
+Copies data from a region of `buf` to a region in `target`, even if the `target`
+memory region overlaps with `buf`.
+
+[`TypedArray.prototype.set()`][] performs the same operation, and is available
+for all TypedArrays, including Node.js `Buffer`s, although it takes
+different function arguments.
+
+```mjs|cjs
+import { Buffer } from 'node:buffer';
+
+// Create two `Buffer` instances.
+const buf1 = Buffer.allocUnsafe(26);
+const buf2 = Buffer.allocUnsafe(26).fill('!');
+
+for (let i = 0; i < 26; i++) {
+ // 97 is the decimal ASCII value for 'a'.
+ buf1[i] = i + 97;
+}
+
+// Copy `buf1` bytes 16 through 19 into `buf2` starting at byte 8 of `buf2`.
+buf1.copy(buf2, 8, 16, 20);
+// This is equivalent to:
+// buf2.set(buf1.subarray(16, 20), 8);
+
+console.log(buf2.toString('ascii', 0, 25));
+// Prints: !!!!!!!!qrst!!!!!!!!!!!!!
+--------------
+const { Buffer } = require('node:buffer');
+
+// Create two `Buffer` instances.
+const buf1 = Buffer.allocUnsafe(26);
+const buf2 = Buffer.allocUnsafe(26).fill('!');
+
+for (let i = 0; i < 26; i++) {
+ // 97 is the decimal ASCII value for 'a'.
+ buf1[i] = i + 97;
+}
+
+// Copy `buf1` bytes 16 through 19 into `buf2` starting at byte 8 of `buf2`.
+buf1.copy(buf2, 8, 16, 20);
+// This is equivalent to:
+// buf2.set(buf1.subarray(16, 20), 8);
+
+console.log(buf2.toString('ascii', 0, 25));
+// Prints: !!!!!!!!qrst!!!!!!!!!!!!!
+```
+
+```mjs|cjs
+import { Buffer } from 'node:buffer';
+
+// Create a `Buffer` and copy data from one region to an overlapping region
+// within the same `Buffer`.
+
+const buf = Buffer.allocUnsafe(26);
+
+for (let i = 0; i < 26; i++) {
+ // 97 is the decimal ASCII value for 'a'.
+ buf[i] = i + 97;
+}
+
+buf.copy(buf, 0, 4, 10);
+
+console.log(buf.toString());
+// Prints: efghijghijklmnopqrstuvwxyz
+--------------
+const { Buffer } = require('node:buffer');
+
+// Create a `Buffer` and copy data from one region to an overlapping region
+// within the same `Buffer`.
+
+const buf = Buffer.allocUnsafe(26);
+
+for (let i = 0; i < 26; i++) {
+ // 97 is the decimal ASCII value for 'a'.
+ buf[i] = i + 97;
+}
+
+buf.copy(buf, 0, 4, 10);
+
+console.log(buf.toString());
+// Prints: efghijghijklmnopqrstuvwxyz
+```
+
+#### `buf.entries()`
+
+
+
+* Returns: [`Iterator`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Iteration_protocols#The_iterator_protocol)
+
+Creates and returns an [iterator][] of `[index, byte]` pairs from the contents
+of `buf`.
+
+```mjs|cjs
+import { Buffer } from 'node:buffer';
+
+// Log the entire contents of a `Buffer`.
+
+const buf = Buffer.from('buffer');
+
+for (const pair of buf.entries()) {
+ console.log(pair);
+}
+// Prints:
+// [0, 98]
+// [1, 117]
+// [2, 102]
+// [3, 102]
+// [4, 101]
+// [5, 114]
+--------------
+const { Buffer } = require('node:buffer');
+
+// Log the entire contents of a `Buffer`.
+
+const buf = Buffer.from('buffer');
+
+for (const pair of buf.entries()) {
+ console.log(pair);
+}
+// Prints:
+// [0, 98]
+// [1, 117]
+// [2, 102]
+// [3, 102]
+// [4, 101]
+// [5, 114]
+```
+
+#### `buf.equals(otherBuffer)`
+
+
+
+* `otherBuffer` [`Buffer`](/api/v16/buffer#buffer) | [`Uint8Array`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Uint8Array) A `Buffer` or [`Uint8Array`][] with which to
+ compare `buf`.
+* Returns: [`boolean`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Boolean_type)
+
+Returns `true` if both `buf` and `otherBuffer` have exactly the same bytes,
+`false` otherwise. Equivalent to
+[`buf.compare(otherBuffer) === 0`][`buf.compare()`].
+
+```mjs|cjs
+import { Buffer } from 'node:buffer';
+
+const buf1 = Buffer.from('ABC');
+const buf2 = Buffer.from('414243', 'hex');
+const buf3 = Buffer.from('ABCD');
+
+console.log(buf1.equals(buf2));
+// Prints: true
+console.log(buf1.equals(buf3));
+// Prints: false
+--------------
+const { Buffer } = require('node:buffer');
+
+const buf1 = Buffer.from('ABC');
+const buf2 = Buffer.from('414243', 'hex');
+const buf3 = Buffer.from('ABCD');
+
+console.log(buf1.equals(buf2));
+// Prints: true
+console.log(buf1.equals(buf3));
+// Prints: false
+```
+
+#### `buf.fill(value[, offset[, end]][, encoding])`
+
+
+
+* `value` [`string`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type) | [`Buffer`](/api/v16/buffer#buffer) | [`Uint8Array`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Uint8Array) | [`integer`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type) The value with which to fill `buf`.
+* `offset` [`integer`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type) Number of bytes to skip before starting to fill `buf`.
+ **Default:** `0`.
+* `end` [`integer`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type) Where to stop filling `buf` (not inclusive). **Default:**
+ [`buf.length`][].
+* `encoding` [`string`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type) The encoding for `value` if `value` is a string.
+ **Default:** `'utf8'`.
+* Returns: [`Buffer`](/api/v16/buffer#buffer) A reference to `buf`.
+
+Fills `buf` with the specified `value`. If the `offset` and `end` are not given,
+the entire `buf` will be filled:
+
+```mjs|cjs
+import { Buffer } from 'node:buffer';
+
+// Fill a `Buffer` with the ASCII character 'h'.
+
+const b = Buffer.allocUnsafe(50).fill('h');
+
+console.log(b.toString());
+// Prints: hhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhh
+--------------
+const { Buffer } = require('node:buffer');
+
+// Fill a `Buffer` with the ASCII character 'h'.
+
+const b = Buffer.allocUnsafe(50).fill('h');
+
+console.log(b.toString());
+// Prints: hhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhh
+```
+
+`value` is coerced to a `uint32` value if it is not a string, `Buffer`, or
+integer. If the resulting integer is greater than `255` (decimal), `buf` will be
+filled with `value & 255`.
+
+If the final write of a `fill()` operation falls on a multi-byte character,
+then only the bytes of that character that fit into `buf` are written:
+
+```mjs|cjs
+import { Buffer } from 'node:buffer';
+
+// Fill a `Buffer` with character that takes up two bytes in UTF-8.
+
+console.log(Buffer.allocUnsafe(5).fill('\u0222'));
+// Prints:
+--------------
+const { Buffer } = require('node:buffer');
+
+// Fill a `Buffer` with character that takes up two bytes in UTF-8.
+
+console.log(Buffer.allocUnsafe(5).fill('\u0222'));
+// Prints:
+```
+
+If `value` contains invalid characters, it is truncated; if no valid
+fill data remains, an exception is thrown:
+
+```mjs|cjs
+import { Buffer } from 'node:buffer';
+
+const buf = Buffer.allocUnsafe(5);
+
+console.log(buf.fill('a'));
+// Prints:
+console.log(buf.fill('aazz', 'hex'));
+// Prints:
+console.log(buf.fill('zz', 'hex'));
+// Throws an exception.
+--------------
+const { Buffer } = require('node:buffer');
+
+const buf = Buffer.allocUnsafe(5);
+
+console.log(buf.fill('a'));
+// Prints:
+console.log(buf.fill('aazz', 'hex'));
+// Prints:
+console.log(buf.fill('zz', 'hex'));
+// Throws an exception.
+```
+
+#### `buf.includes(value[, byteOffset][, encoding])`
+
+
+
+* `value` [`string`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type) | [`Buffer`](/api/v16/buffer#buffer) | [`Uint8Array`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Uint8Array) | [`integer`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type) What to search for.
+* `byteOffset` [`integer`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type) Where to begin searching in `buf`. If negative, then
+ offset is calculated from the end of `buf`. **Default:** `0`.
+* `encoding` [`string`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type) If `value` is a string, this is its encoding.
+ **Default:** `'utf8'`.
+* Returns: [`boolean`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Boolean_type) `true` if `value` was found in `buf`, `false` otherwise.
+
+Equivalent to [`buf.indexOf() !== -1`][`buf.indexOf()`].
+
+```mjs|cjs
+import { Buffer } from 'node:buffer';
+
+const buf = Buffer.from('this is a buffer');
+
+console.log(buf.includes('this'));
+// Prints: true
+console.log(buf.includes('is'));
+// Prints: true
+console.log(buf.includes(Buffer.from('a buffer')));
+// Prints: true
+console.log(buf.includes(97));
+// Prints: true (97 is the decimal ASCII value for 'a')
+console.log(buf.includes(Buffer.from('a buffer example')));
+// Prints: false
+console.log(buf.includes(Buffer.from('a buffer example').slice(0, 8)));
+// Prints: true
+console.log(buf.includes('this', 4));
+// Prints: false
+--------------
+const { Buffer } = require('node:buffer');
+
+const buf = Buffer.from('this is a buffer');
+
+console.log(buf.includes('this'));
+// Prints: true
+console.log(buf.includes('is'));
+// Prints: true
+console.log(buf.includes(Buffer.from('a buffer')));
+// Prints: true
+console.log(buf.includes(97));
+// Prints: true (97 is the decimal ASCII value for 'a')
+console.log(buf.includes(Buffer.from('a buffer example')));
+// Prints: false
+console.log(buf.includes(Buffer.from('a buffer example').slice(0, 8)));
+// Prints: true
+console.log(buf.includes('this', 4));
+// Prints: false
+```
+
+#### `buf.indexOf(value[, byteOffset][, encoding])`
+
+
+
+* `value` [`string`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type) | [`Buffer`](/api/v16/buffer#buffer) | [`Uint8Array`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Uint8Array) | [`integer`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type) What to search for.
+* `byteOffset` [`integer`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type) Where to begin searching in `buf`. If negative, then
+ offset is calculated from the end of `buf`. **Default:** `0`.
+* `encoding` [`string`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type) If `value` is a string, this is the encoding used to
+ determine the binary representation of the string that will be searched for in
+ `buf`. **Default:** `'utf8'`.
+* Returns: [`integer`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type) The index of the first occurrence of `value` in `buf`, or
+ `-1` if `buf` does not contain `value`.
+
+If `value` is:
+
+* a string, `value` is interpreted according to the character encoding in
+ `encoding`.
+* a `Buffer` or [`Uint8Array`][], `value` will be used in its entirety.
+ To compare a partial `Buffer`, use [`buf.subarray`][].
+* a number, `value` will be interpreted as an unsigned 8-bit integer
+ value between `0` and `255`.
+
+```mjs|cjs
+import { Buffer } from 'node:buffer';
+
+const buf = Buffer.from('this is a buffer');
+
+console.log(buf.indexOf('this'));
+// Prints: 0
+console.log(buf.indexOf('is'));
+// Prints: 2
+console.log(buf.indexOf(Buffer.from('a buffer')));
+// Prints: 8
+console.log(buf.indexOf(97));
+// Prints: 8 (97 is the decimal ASCII value for 'a')
+console.log(buf.indexOf(Buffer.from('a buffer example')));
+// Prints: -1
+console.log(buf.indexOf(Buffer.from('a buffer example').slice(0, 8)));
+// Prints: 8
+
+const utf16Buffer = Buffer.from('\u039a\u0391\u03a3\u03a3\u0395', 'utf16le');
+
+console.log(utf16Buffer.indexOf('\u03a3', 0, 'utf16le'));
+// Prints: 4
+console.log(utf16Buffer.indexOf('\u03a3', -4, 'utf16le'));
+// Prints: 6
+--------------
+const { Buffer } = require('node:buffer');
+
+const buf = Buffer.from('this is a buffer');
+
+console.log(buf.indexOf('this'));
+// Prints: 0
+console.log(buf.indexOf('is'));
+// Prints: 2
+console.log(buf.indexOf(Buffer.from('a buffer')));
+// Prints: 8
+console.log(buf.indexOf(97));
+// Prints: 8 (97 is the decimal ASCII value for 'a')
+console.log(buf.indexOf(Buffer.from('a buffer example')));
+// Prints: -1
+console.log(buf.indexOf(Buffer.from('a buffer example').slice(0, 8)));
+// Prints: 8
+
+const utf16Buffer = Buffer.from('\u039a\u0391\u03a3\u03a3\u0395', 'utf16le');
+
+console.log(utf16Buffer.indexOf('\u03a3', 0, 'utf16le'));
+// Prints: 4
+console.log(utf16Buffer.indexOf('\u03a3', -4, 'utf16le'));
+// Prints: 6
+```
+
+If `value` is not a string, number, or `Buffer`, this method will throw a
+`TypeError`. If `value` is a number, it will be coerced to a valid byte value,
+an integer between 0 and 255.
+
+If `byteOffset` is not a number, it will be coerced to a number. If the result
+of coercion is `NaN` or `0`, then the entire buffer will be searched. This
+behavior matches [`String.prototype.indexOf()`][].
+
+```mjs|cjs
+import { Buffer } from 'node:buffer';
+
+const b = Buffer.from('abcdef');
+
+// Passing a value that's a number, but not a valid byte.
+// Prints: 2, equivalent to searching for 99 or 'c'.
+console.log(b.indexOf(99.9));
+console.log(b.indexOf(256 + 99));
+
+// Passing a byteOffset that coerces to NaN or 0.
+// Prints: 1, searching the whole buffer.
+console.log(b.indexOf('b', undefined));
+console.log(b.indexOf('b', {}));
+console.log(b.indexOf('b', null));
+console.log(b.indexOf('b', []));
+--------------
+const { Buffer } = require('node:buffer');
+
+const b = Buffer.from('abcdef');
+
+// Passing a value that's a number, but not a valid byte.
+// Prints: 2, equivalent to searching for 99 or 'c'.
+console.log(b.indexOf(99.9));
+console.log(b.indexOf(256 + 99));
+
+// Passing a byteOffset that coerces to NaN or 0.
+// Prints: 1, searching the whole buffer.
+console.log(b.indexOf('b', undefined));
+console.log(b.indexOf('b', {}));
+console.log(b.indexOf('b', null));
+console.log(b.indexOf('b', []));
+```
+
+If `value` is an empty string or empty `Buffer` and `byteOffset` is less
+than `buf.length`, `byteOffset` will be returned. If `value` is empty and
+`byteOffset` is at least `buf.length`, `buf.length` will be returned.
+
+#### `buf.keys()`
+
+
+
+* Returns: [`Iterator`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Iteration_protocols#The_iterator_protocol)
+
+Creates and returns an [iterator][] of `buf` keys (indices).
+
+```mjs|cjs
+import { Buffer } from 'node:buffer';
+
+const buf = Buffer.from('buffer');
+
+for (const key of buf.keys()) {
+ console.log(key);
+}
+// Prints:
+// 0
+// 1
+// 2
+// 3
+// 4
+// 5
+--------------
+const { Buffer } = require('node:buffer');
+
+const buf = Buffer.from('buffer');
+
+for (const key of buf.keys()) {
+ console.log(key);
+}
+// Prints:
+// 0
+// 1
+// 2
+// 3
+// 4
+// 5
+```
+
+#### `buf.lastIndexOf(value[, byteOffset][, encoding])`
+
+
+
+* `value` [`string`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type) | [`Buffer`](/api/v16/buffer#buffer) | [`Uint8Array`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Uint8Array) | [`integer`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type) What to search for.
+* `byteOffset` [`integer`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type) Where to begin searching in `buf`. If negative, then
+ offset is calculated from the end of `buf`. **Default:**
+ `buf.length - 1`.
+* `encoding` [`string`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type) If `value` is a string, this is the encoding used to
+ determine the binary representation of the string that will be searched for in
+ `buf`. **Default:** `'utf8'`.
+* Returns: [`integer`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type) The index of the last occurrence of `value` in `buf`, or
+ `-1` if `buf` does not contain `value`.
+
+Identical to [`buf.indexOf()`][], except the last occurrence of `value` is found
+rather than the first occurrence.
+
+```mjs|cjs
+import { Buffer } from 'node:buffer';
+
+const buf = Buffer.from('this buffer is a buffer');
+
+console.log(buf.lastIndexOf('this'));
+// Prints: 0
+console.log(buf.lastIndexOf('buffer'));
+// Prints: 17
+console.log(buf.lastIndexOf(Buffer.from('buffer')));
+// Prints: 17
+console.log(buf.lastIndexOf(97));
+// Prints: 15 (97 is the decimal ASCII value for 'a')
+console.log(buf.lastIndexOf(Buffer.from('yolo')));
+// Prints: -1
+console.log(buf.lastIndexOf('buffer', 5));
+// Prints: 5
+console.log(buf.lastIndexOf('buffer', 4));
+// Prints: -1
+
+const utf16Buffer = Buffer.from('\u039a\u0391\u03a3\u03a3\u0395', 'utf16le');
+
+console.log(utf16Buffer.lastIndexOf('\u03a3', undefined, 'utf16le'));
+// Prints: 6
+console.log(utf16Buffer.lastIndexOf('\u03a3', -5, 'utf16le'));
+// Prints: 4
+--------------
+const { Buffer } = require('node:buffer');
+
+const buf = Buffer.from('this buffer is a buffer');
+
+console.log(buf.lastIndexOf('this'));
+// Prints: 0
+console.log(buf.lastIndexOf('buffer'));
+// Prints: 17
+console.log(buf.lastIndexOf(Buffer.from('buffer')));
+// Prints: 17
+console.log(buf.lastIndexOf(97));
+// Prints: 15 (97 is the decimal ASCII value for 'a')
+console.log(buf.lastIndexOf(Buffer.from('yolo')));
+// Prints: -1
+console.log(buf.lastIndexOf('buffer', 5));
+// Prints: 5
+console.log(buf.lastIndexOf('buffer', 4));
+// Prints: -1
+
+const utf16Buffer = Buffer.from('\u039a\u0391\u03a3\u03a3\u0395', 'utf16le');
+
+console.log(utf16Buffer.lastIndexOf('\u03a3', undefined, 'utf16le'));
+// Prints: 6
+console.log(utf16Buffer.lastIndexOf('\u03a3', -5, 'utf16le'));
+// Prints: 4
+```
+
+If `value` is not a string, number, or `Buffer`, this method will throw a
+`TypeError`. If `value` is a number, it will be coerced to a valid byte value,
+an integer between 0 and 255.
+
+If `byteOffset` is not a number, it will be coerced to a number. Any arguments
+that coerce to `NaN`, like `{}` or `undefined`, will search the whole buffer.
+This behavior matches [`String.prototype.lastIndexOf()`][].
+
+```mjs|cjs
+import { Buffer } from 'node:buffer';
+
+const b = Buffer.from('abcdef');
+
+// Passing a value that's a number, but not a valid byte.
+// Prints: 2, equivalent to searching for 99 or 'c'.
+console.log(b.lastIndexOf(99.9));
+console.log(b.lastIndexOf(256 + 99));
+
+// Passing a byteOffset that coerces to NaN.
+// Prints: 1, searching the whole buffer.
+console.log(b.lastIndexOf('b', undefined));
+console.log(b.lastIndexOf('b', {}));
+
+// Passing a byteOffset that coerces to 0.
+// Prints: -1, equivalent to passing 0.
+console.log(b.lastIndexOf('b', null));
+console.log(b.lastIndexOf('b', []));
+--------------
+const { Buffer } = require('node:buffer');
+
+const b = Buffer.from('abcdef');
+
+// Passing a value that's a number, but not a valid byte.
+// Prints: 2, equivalent to searching for 99 or 'c'.
+console.log(b.lastIndexOf(99.9));
+console.log(b.lastIndexOf(256 + 99));
+
+// Passing a byteOffset that coerces to NaN.
+// Prints: 1, searching the whole buffer.
+console.log(b.lastIndexOf('b', undefined));
+console.log(b.lastIndexOf('b', {}));
+
+// Passing a byteOffset that coerces to 0.
+// Prints: -1, equivalent to passing 0.
+console.log(b.lastIndexOf('b', null));
+console.log(b.lastIndexOf('b', []));
+```
+
+If `value` is an empty string or empty `Buffer`, `byteOffset` will be returned.
+
+#### `buf.length`
+
+
+
+* [`integer`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type)
+
+Returns the number of bytes in `buf`.
+
+```mjs|cjs
+import { Buffer } from 'node:buffer';
+
+// Create a `Buffer` and write a shorter string to it using UTF-8.
+
+const buf = Buffer.alloc(1234);
+
+console.log(buf.length);
+// Prints: 1234
+
+buf.write('some string', 0, 'utf8');
+
+console.log(buf.length);
+// Prints: 1234
+--------------
+const { Buffer } = require('node:buffer');
+
+// Create a `Buffer` and write a shorter string to it using UTF-8.
+
+const buf = Buffer.alloc(1234);
+
+console.log(buf.length);
+// Prints: 1234
+
+buf.write('some string', 0, 'utf8');
+
+console.log(buf.length);
+// Prints: 1234
+```
+
+#### `buf.parent`
+
+
+
+
+
+Deprecated: Use [`buf.buffer`][] instead.
+
+
+
+The `buf.parent` property is a deprecated alias for `buf.buffer`.
+
+#### `buf.readBigInt64BE([offset])`
+
+
+
+* `offset` [`integer`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type) Number of bytes to skip before starting to read. Must
+ satisfy: `0 <= offset <= buf.length - 8`. **Default:** `0`.
+* Returns: [`bigint`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/BigInt)
+
+Reads a signed, big-endian 64-bit integer from `buf` at the specified `offset`.
+
+Integers read from a `Buffer` are interpreted as two's complement signed
+values.
+
+#### `buf.readBigInt64LE([offset])`
+
+
+
+* `offset` [`integer`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type) Number of bytes to skip before starting to read. Must
+ satisfy: `0 <= offset <= buf.length - 8`. **Default:** `0`.
+* Returns: [`bigint`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/BigInt)
+
+Reads a signed, little-endian 64-bit integer from `buf` at the specified
+`offset`.
+
+Integers read from a `Buffer` are interpreted as two's complement signed
+values.
+
+#### `buf.readBigUInt64BE([offset])`
+
+
+
+* `offset` [`integer`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type) Number of bytes to skip before starting to read. Must
+ satisfy: `0 <= offset <= buf.length - 8`. **Default:** `0`.
+* Returns: [`bigint`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/BigInt)
+
+Reads an unsigned, big-endian 64-bit integer from `buf` at the specified
+`offset`.
+
+This function is also available under the `readBigUint64BE` alias.
+
+```mjs|cjs
+import { Buffer } from 'node:buffer';
+
+const buf = Buffer.from([0x00, 0x00, 0x00, 0x00, 0xff, 0xff, 0xff, 0xff]);
+
+console.log(buf.readBigUInt64BE(0));
+// Prints: 4294967295n
+--------------
+const { Buffer } = require('node:buffer');
+
+const buf = Buffer.from([0x00, 0x00, 0x00, 0x00, 0xff, 0xff, 0xff, 0xff]);
+
+console.log(buf.readBigUInt64BE(0));
+// Prints: 4294967295n
+```
+
+#### `buf.readBigUInt64LE([offset])`
+
+
+
+* `offset` [`integer`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type) Number of bytes to skip before starting to read. Must
+ satisfy: `0 <= offset <= buf.length - 8`. **Default:** `0`.
+* Returns: [`bigint`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/BigInt)
+
+Reads an unsigned, little-endian 64-bit integer from `buf` at the specified
+`offset`.
+
+This function is also available under the `readBigUint64LE` alias.
+
+```mjs|cjs
+import { Buffer } from 'node:buffer';
+
+const buf = Buffer.from([0x00, 0x00, 0x00, 0x00, 0xff, 0xff, 0xff, 0xff]);
+
+console.log(buf.readBigUInt64LE(0));
+// Prints: 18446744069414584320n
+--------------
+const { Buffer } = require('node:buffer');
+
+const buf = Buffer.from([0x00, 0x00, 0x00, 0x00, 0xff, 0xff, 0xff, 0xff]);
+
+console.log(buf.readBigUInt64LE(0));
+// Prints: 18446744069414584320n
+```
+
+#### `buf.readDoubleBE([offset])`
+
+
+
+* `offset` [`integer`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type) Number of bytes to skip before starting to read. Must
+ satisfy `0 <= offset <= buf.length - 8`. **Default:** `0`.
+* Returns: [`number`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type)
+
+Reads a 64-bit, big-endian double from `buf` at the specified `offset`.
+
+```mjs|cjs
+import { Buffer } from 'node:buffer';
+
+const buf = Buffer.from([1, 2, 3, 4, 5, 6, 7, 8]);
+
+console.log(buf.readDoubleBE(0));
+// Prints: 8.20788039913184e-304
+--------------
+const { Buffer } = require('node:buffer');
+
+const buf = Buffer.from([1, 2, 3, 4, 5, 6, 7, 8]);
+
+console.log(buf.readDoubleBE(0));
+// Prints: 8.20788039913184e-304
+```
+
+#### `buf.readDoubleLE([offset])`
+
+
+
+* `offset` [`integer`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type) Number of bytes to skip before starting to read. Must
+ satisfy `0 <= offset <= buf.length - 8`. **Default:** `0`.
+* Returns: [`number`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type)
+
+Reads a 64-bit, little-endian double from `buf` at the specified `offset`.
+
+```mjs|cjs
+import { Buffer } from 'node:buffer';
+
+const buf = Buffer.from([1, 2, 3, 4, 5, 6, 7, 8]);
+
+console.log(buf.readDoubleLE(0));
+// Prints: 5.447603722011605e-270
+console.log(buf.readDoubleLE(1));
+// Throws ERR_OUT_OF_RANGE.
+--------------
+const { Buffer } = require('node:buffer');
+
+const buf = Buffer.from([1, 2, 3, 4, 5, 6, 7, 8]);
+
+console.log(buf.readDoubleLE(0));
+// Prints: 5.447603722011605e-270
+console.log(buf.readDoubleLE(1));
+// Throws ERR_OUT_OF_RANGE.
+```
+
+#### `buf.readFloatBE([offset])`
+
+
+
+* `offset` [`integer`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type) Number of bytes to skip before starting to read. Must
+ satisfy `0 <= offset <= buf.length - 4`. **Default:** `0`.
+* Returns: [`number`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type)
+
+Reads a 32-bit, big-endian float from `buf` at the specified `offset`.
+
+```mjs|cjs
+import { Buffer } from 'node:buffer';
+
+const buf = Buffer.from([1, 2, 3, 4]);
+
+console.log(buf.readFloatBE(0));
+// Prints: 2.387939260590663e-38
+--------------
+const { Buffer } = require('node:buffer');
+
+const buf = Buffer.from([1, 2, 3, 4]);
+
+console.log(buf.readFloatBE(0));
+// Prints: 2.387939260590663e-38
+```
+
+#### `buf.readFloatLE([offset])`
+
+
+
+* `offset` [`integer`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type) Number of bytes to skip before starting to read. Must
+ satisfy `0 <= offset <= buf.length - 4`. **Default:** `0`.
+* Returns: [`number`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type)
+
+Reads a 32-bit, little-endian float from `buf` at the specified `offset`.
+
+```mjs|cjs
+import { Buffer } from 'node:buffer';
+
+const buf = Buffer.from([1, 2, 3, 4]);
+
+console.log(buf.readFloatLE(0));
+// Prints: 1.539989614439558e-36
+console.log(buf.readFloatLE(1));
+// Throws ERR_OUT_OF_RANGE.
+--------------
+const { Buffer } = require('node:buffer');
+
+const buf = Buffer.from([1, 2, 3, 4]);
+
+console.log(buf.readFloatLE(0));
+// Prints: 1.539989614439558e-36
+console.log(buf.readFloatLE(1));
+// Throws ERR_OUT_OF_RANGE.
+```
+
+#### `buf.readInt8([offset])`
+
+
+
+* `offset` [`integer`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type) Number of bytes to skip before starting to read. Must
+ satisfy `0 <= offset <= buf.length - 1`. **Default:** `0`.
+* Returns: [`integer`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type)
+
+Reads a signed 8-bit integer from `buf` at the specified `offset`.
+
+Integers read from a `Buffer` are interpreted as two's complement signed values.
+
+```mjs|cjs
+import { Buffer } from 'node:buffer';
+
+const buf = Buffer.from([-1, 5]);
+
+console.log(buf.readInt8(0));
+// Prints: -1
+console.log(buf.readInt8(1));
+// Prints: 5
+console.log(buf.readInt8(2));
+// Throws ERR_OUT_OF_RANGE.
+--------------
+const { Buffer } = require('node:buffer');
+
+const buf = Buffer.from([-1, 5]);
+
+console.log(buf.readInt8(0));
+// Prints: -1
+console.log(buf.readInt8(1));
+// Prints: 5
+console.log(buf.readInt8(2));
+// Throws ERR_OUT_OF_RANGE.
+```
+
+#### `buf.readInt16BE([offset])`
+
+
+
+* `offset` [`integer`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type) Number of bytes to skip before starting to read. Must
+ satisfy `0 <= offset <= buf.length - 2`. **Default:** `0`.
+* Returns: [`integer`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type)
+
+Reads a signed, big-endian 16-bit integer from `buf` at the specified `offset`.
+
+Integers read from a `Buffer` are interpreted as two's complement signed values.
+
+```mjs|cjs
+import { Buffer } from 'node:buffer';
+
+const buf = Buffer.from([0, 5]);
+
+console.log(buf.readInt16BE(0));
+// Prints: 5
+--------------
+const { Buffer } = require('node:buffer');
+
+const buf = Buffer.from([0, 5]);
+
+console.log(buf.readInt16BE(0));
+// Prints: 5
+```
+
+#### `buf.readInt16LE([offset])`
+
+
+
+* `offset` [`integer`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type) Number of bytes to skip before starting to read. Must
+ satisfy `0 <= offset <= buf.length - 2`. **Default:** `0`.
+* Returns: [`integer`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type)
+
+Reads a signed, little-endian 16-bit integer from `buf` at the specified
+`offset`.
+
+Integers read from a `Buffer` are interpreted as two's complement signed values.
+
+```mjs|cjs
+import { Buffer } from 'node:buffer';
+
+const buf = Buffer.from([0, 5]);
+
+console.log(buf.readInt16LE(0));
+// Prints: 1280
+console.log(buf.readInt16LE(1));
+// Throws ERR_OUT_OF_RANGE.
+--------------
+const { Buffer } = require('node:buffer');
+
+const buf = Buffer.from([0, 5]);
+
+console.log(buf.readInt16LE(0));
+// Prints: 1280
+console.log(buf.readInt16LE(1));
+// Throws ERR_OUT_OF_RANGE.
+```
+
+#### `buf.readInt32BE([offset])`
+
+
+
+* `offset` [`integer`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type) Number of bytes to skip before starting to read. Must
+ satisfy `0 <= offset <= buf.length - 4`. **Default:** `0`.
+* Returns: [`integer`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type)
+
+Reads a signed, big-endian 32-bit integer from `buf` at the specified `offset`.
+
+Integers read from a `Buffer` are interpreted as two's complement signed values.
+
+```mjs|cjs
+import { Buffer } from 'node:buffer';
+
+const buf = Buffer.from([0, 0, 0, 5]);
+
+console.log(buf.readInt32BE(0));
+// Prints: 5
+--------------
+const { Buffer } = require('node:buffer');
+
+const buf = Buffer.from([0, 0, 0, 5]);
+
+console.log(buf.readInt32BE(0));
+// Prints: 5
+```
+
+#### `buf.readInt32LE([offset])`
+
+
+
+* `offset` [`integer`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type) Number of bytes to skip before starting to read. Must
+ satisfy `0 <= offset <= buf.length - 4`. **Default:** `0`.
+* Returns: [`integer`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type)
+
+Reads a signed, little-endian 32-bit integer from `buf` at the specified
+`offset`.
+
+Integers read from a `Buffer` are interpreted as two's complement signed values.
+
+```mjs|cjs
+import { Buffer } from 'node:buffer';
+
+const buf = Buffer.from([0, 0, 0, 5]);
+
+console.log(buf.readInt32LE(0));
+// Prints: 83886080
+console.log(buf.readInt32LE(1));
+// Throws ERR_OUT_OF_RANGE.
+--------------
+const { Buffer } = require('node:buffer');
+
+const buf = Buffer.from([0, 0, 0, 5]);
+
+console.log(buf.readInt32LE(0));
+// Prints: 83886080
+console.log(buf.readInt32LE(1));
+// Throws ERR_OUT_OF_RANGE.
+```
+
+#### `buf.readIntBE(offset, byteLength)`
+
+
+
+* `offset` [`integer`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type) Number of bytes to skip before starting to read. Must
+ satisfy `0 <= offset <= buf.length - byteLength`.
+* `byteLength` [`integer`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type) Number of bytes to read. Must satisfy
+ `0 < byteLength <= 6`.
+* Returns: [`integer`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type)
+
+Reads `byteLength` number of bytes from `buf` at the specified `offset`
+and interprets the result as a big-endian, two's complement signed value
+supporting up to 48 bits of accuracy.
+
+```mjs|cjs
+import { Buffer } from 'node:buffer';
+
+const buf = Buffer.from([0x12, 0x34, 0x56, 0x78, 0x90, 0xab]);
+
+console.log(buf.readIntBE(0, 6).toString(16));
+// Prints: 1234567890ab
+console.log(buf.readIntBE(1, 6).toString(16));
+// Throws ERR_OUT_OF_RANGE.
+console.log(buf.readIntBE(1, 0).toString(16));
+// Throws ERR_OUT_OF_RANGE.
+--------------
+const { Buffer } = require('node:buffer');
+
+const buf = Buffer.from([0x12, 0x34, 0x56, 0x78, 0x90, 0xab]);
+
+console.log(buf.readIntBE(0, 6).toString(16));
+// Prints: 1234567890ab
+console.log(buf.readIntBE(1, 6).toString(16));
+// Throws ERR_OUT_OF_RANGE.
+console.log(buf.readIntBE(1, 0).toString(16));
+// Throws ERR_OUT_OF_RANGE.
+```
+
+#### `buf.readIntLE(offset, byteLength)`
+
+
+
+* `offset` [`integer`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type) Number of bytes to skip before starting to read. Must
+ satisfy `0 <= offset <= buf.length - byteLength`.
+* `byteLength` [`integer`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type) Number of bytes to read. Must satisfy
+ `0 < byteLength <= 6`.
+* Returns: [`integer`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type)
+
+Reads `byteLength` number of bytes from `buf` at the specified `offset`
+and interprets the result as a little-endian, two's complement signed value
+supporting up to 48 bits of accuracy.
+
+```mjs|cjs
+import { Buffer } from 'node:buffer';
+
+const buf = Buffer.from([0x12, 0x34, 0x56, 0x78, 0x90, 0xab]);
+
+console.log(buf.readIntLE(0, 6).toString(16));
+// Prints: -546f87a9cbee
+--------------
+const { Buffer } = require('node:buffer');
+
+const buf = Buffer.from([0x12, 0x34, 0x56, 0x78, 0x90, 0xab]);
+
+console.log(buf.readIntLE(0, 6).toString(16));
+// Prints: -546f87a9cbee
+```
+
+#### `buf.readUInt8([offset])`
+
+
+
+* `offset` [`integer`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type) Number of bytes to skip before starting to read. Must
+ satisfy `0 <= offset <= buf.length - 1`. **Default:** `0`.
+* Returns: [`integer`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type)
+
+Reads an unsigned 8-bit integer from `buf` at the specified `offset`.
+
+This function is also available under the `readUint8` alias.
+
+```mjs|cjs
+import { Buffer } from 'node:buffer';
+
+const buf = Buffer.from([1, -2]);
+
+console.log(buf.readUInt8(0));
+// Prints: 1
+console.log(buf.readUInt8(1));
+// Prints: 254
+console.log(buf.readUInt8(2));
+// Throws ERR_OUT_OF_RANGE.
+--------------
+const { Buffer } = require('node:buffer');
+
+const buf = Buffer.from([1, -2]);
+
+console.log(buf.readUInt8(0));
+// Prints: 1
+console.log(buf.readUInt8(1));
+// Prints: 254
+console.log(buf.readUInt8(2));
+// Throws ERR_OUT_OF_RANGE.
+```
+
+#### `buf.readUInt16BE([offset])`
+
+
+
+* `offset` [`integer`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type) Number of bytes to skip before starting to read. Must
+ satisfy `0 <= offset <= buf.length - 2`. **Default:** `0`.
+* Returns: [`integer`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type)
+
+Reads an unsigned, big-endian 16-bit integer from `buf` at the specified
+`offset`.
+
+This function is also available under the `readUint16BE` alias.
+
+```mjs|cjs
+import { Buffer } from 'node:buffer';
+
+const buf = Buffer.from([0x12, 0x34, 0x56]);
+
+console.log(buf.readUInt16BE(0).toString(16));
+// Prints: 1234
+console.log(buf.readUInt16BE(1).toString(16));
+// Prints: 3456
+--------------
+const { Buffer } = require('node:buffer');
+
+const buf = Buffer.from([0x12, 0x34, 0x56]);
+
+console.log(buf.readUInt16BE(0).toString(16));
+// Prints: 1234
+console.log(buf.readUInt16BE(1).toString(16));
+// Prints: 3456
+```
+
+#### `buf.readUInt16LE([offset])`
+
+
+
+* `offset` [`integer`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type) Number of bytes to skip before starting to read. Must
+ satisfy `0 <= offset <= buf.length - 2`. **Default:** `0`.
+* Returns: [`integer`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type)
+
+Reads an unsigned, little-endian 16-bit integer from `buf` at the specified
+`offset`.
+
+This function is also available under the `readUint16LE` alias.
+
+```mjs|cjs
+import { Buffer } from 'node:buffer';
+
+const buf = Buffer.from([0x12, 0x34, 0x56]);
+
+console.log(buf.readUInt16LE(0).toString(16));
+// Prints: 3412
+console.log(buf.readUInt16LE(1).toString(16));
+// Prints: 5634
+console.log(buf.readUInt16LE(2).toString(16));
+// Throws ERR_OUT_OF_RANGE.
+--------------
+const { Buffer } = require('node:buffer');
+
+const buf = Buffer.from([0x12, 0x34, 0x56]);
+
+console.log(buf.readUInt16LE(0).toString(16));
+// Prints: 3412
+console.log(buf.readUInt16LE(1).toString(16));
+// Prints: 5634
+console.log(buf.readUInt16LE(2).toString(16));
+// Throws ERR_OUT_OF_RANGE.
+```
+
+#### `buf.readUInt32BE([offset])`
+
+
+
+* `offset` [`integer`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type) Number of bytes to skip before starting to read. Must
+ satisfy `0 <= offset <= buf.length - 4`. **Default:** `0`.
+* Returns: [`integer`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type)
+
+Reads an unsigned, big-endian 32-bit integer from `buf` at the specified
+`offset`.
+
+This function is also available under the `readUint32BE` alias.
+
+```mjs|cjs
+import { Buffer } from 'node:buffer';
+
+const buf = Buffer.from([0x12, 0x34, 0x56, 0x78]);
+
+console.log(buf.readUInt32BE(0).toString(16));
+// Prints: 12345678
+--------------
+const { Buffer } = require('node:buffer');
+
+const buf = Buffer.from([0x12, 0x34, 0x56, 0x78]);
+
+console.log(buf.readUInt32BE(0).toString(16));
+// Prints: 12345678
+```
+
+#### `buf.readUInt32LE([offset])`
+
+
+
+* `offset` [`integer`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type) Number of bytes to skip before starting to read. Must
+ satisfy `0 <= offset <= buf.length - 4`. **Default:** `0`.
+* Returns: [`integer`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type)
+
+Reads an unsigned, little-endian 32-bit integer from `buf` at the specified
+`offset`.
+
+This function is also available under the `readUint32LE` alias.
+
+```mjs|cjs
+import { Buffer } from 'node:buffer';
+
+const buf = Buffer.from([0x12, 0x34, 0x56, 0x78]);
+
+console.log(buf.readUInt32LE(0).toString(16));
+// Prints: 78563412
+console.log(buf.readUInt32LE(1).toString(16));
+// Throws ERR_OUT_OF_RANGE.
+--------------
+const { Buffer } = require('node:buffer');
+
+const buf = Buffer.from([0x12, 0x34, 0x56, 0x78]);
+
+console.log(buf.readUInt32LE(0).toString(16));
+// Prints: 78563412
+console.log(buf.readUInt32LE(1).toString(16));
+// Throws ERR_OUT_OF_RANGE.
+```
+
+#### `buf.readUIntBE(offset, byteLength)`
+
+
+
+* `offset` [`integer`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type) Number of bytes to skip before starting to read. Must
+ satisfy `0 <= offset <= buf.length - byteLength`.
+* `byteLength` [`integer`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type) Number of bytes to read. Must satisfy
+ `0 < byteLength <= 6`.
+* Returns: [`integer`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type)
+
+Reads `byteLength` number of bytes from `buf` at the specified `offset`
+and interprets the result as an unsigned big-endian integer supporting
+up to 48 bits of accuracy.
+
+This function is also available under the `readUintBE` alias.
+
+```mjs|cjs
+import { Buffer } from 'node:buffer';
+
+const buf = Buffer.from([0x12, 0x34, 0x56, 0x78, 0x90, 0xab]);
+
+console.log(buf.readUIntBE(0, 6).toString(16));
+// Prints: 1234567890ab
+console.log(buf.readUIntBE(1, 6).toString(16));
+// Throws ERR_OUT_OF_RANGE.
+--------------
+const { Buffer } = require('node:buffer');
+
+const buf = Buffer.from([0x12, 0x34, 0x56, 0x78, 0x90, 0xab]);
+
+console.log(buf.readUIntBE(0, 6).toString(16));
+// Prints: 1234567890ab
+console.log(buf.readUIntBE(1, 6).toString(16));
+// Throws ERR_OUT_OF_RANGE.
+```
+
+#### `buf.readUIntLE(offset, byteLength)`
+
+
+
+* `offset` [`integer`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type) Number of bytes to skip before starting to read. Must
+ satisfy `0 <= offset <= buf.length - byteLength`.
+* `byteLength` [`integer`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type) Number of bytes to read. Must satisfy
+ `0 < byteLength <= 6`.
+* Returns: [`integer`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type)
+
+Reads `byteLength` number of bytes from `buf` at the specified `offset`
+and interprets the result as an unsigned, little-endian integer supporting
+up to 48 bits of accuracy.
+
+This function is also available under the `readUintLE` alias.
+
+```mjs|cjs
+import { Buffer } from 'node:buffer';
+
+const buf = Buffer.from([0x12, 0x34, 0x56, 0x78, 0x90, 0xab]);
+
+console.log(buf.readUIntLE(0, 6).toString(16));
+// Prints: ab9078563412
+--------------
+const { Buffer } = require('node:buffer');
+
+const buf = Buffer.from([0x12, 0x34, 0x56, 0x78, 0x90, 0xab]);
+
+console.log(buf.readUIntLE(0, 6).toString(16));
+// Prints: ab9078563412
+```
+
+#### `buf.subarray([start[, end]])`
+
+
+
+* `start` [`integer`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type) Where the new `Buffer` will start. **Default:** `0`.
+* `end` [`integer`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type) Where the new `Buffer` will end (not inclusive).
+ **Default:** [`buf.length`][].
+* Returns: [`Buffer`](/api/v16/buffer#buffer)
+
+Returns a new `Buffer` that references the same memory as the original, but
+offset and cropped by the `start` and `end` indices.
+
+Specifying `end` greater than [`buf.length`][] will return the same result as
+that of `end` equal to [`buf.length`][].
+
+This method is inherited from [`TypedArray.prototype.subarray()`][].
+
+Modifying the new `Buffer` slice will modify the memory in the original `Buffer`
+because the allocated memory of the two objects overlap.
+
+```mjs|cjs
+import { Buffer } from 'node:buffer';
+
+// Create a `Buffer` with the ASCII alphabet, take a slice, and modify one byte
+// from the original `Buffer`.
+
+const buf1 = Buffer.allocUnsafe(26);
+
+for (let i = 0; i < 26; i++) {
+ // 97 is the decimal ASCII value for 'a'.
+ buf1[i] = i + 97;
+}
+
+const buf2 = buf1.subarray(0, 3);
+
+console.log(buf2.toString('ascii', 0, buf2.length));
+// Prints: abc
+
+buf1[0] = 33;
+
+console.log(buf2.toString('ascii', 0, buf2.length));
+// Prints: !bc
+--------------
+const { Buffer } = require('node:buffer');
+
+// Create a `Buffer` with the ASCII alphabet, take a slice, and modify one byte
+// from the original `Buffer`.
+
+const buf1 = Buffer.allocUnsafe(26);
+
+for (let i = 0; i < 26; i++) {
+ // 97 is the decimal ASCII value for 'a'.
+ buf1[i] = i + 97;
+}
+
+const buf2 = buf1.subarray(0, 3);
+
+console.log(buf2.toString('ascii', 0, buf2.length));
+// Prints: abc
+
+buf1[0] = 33;
+
+console.log(buf2.toString('ascii', 0, buf2.length));
+// Prints: !bc
+```
+
+Specifying negative indexes causes the slice to be generated relative to the
+end of `buf` rather than the beginning.
+
+```mjs|cjs
+import { Buffer } from 'node:buffer';
+
+const buf = Buffer.from('buffer');
+
+console.log(buf.subarray(-6, -1).toString());
+// Prints: buffe
+// (Equivalent to buf.subarray(0, 5).)
+
+console.log(buf.subarray(-6, -2).toString());
+// Prints: buff
+// (Equivalent to buf.subarray(0, 4).)
+
+console.log(buf.subarray(-5, -2).toString());
+// Prints: uff
+// (Equivalent to buf.subarray(1, 4).)
+--------------
+const { Buffer } = require('node:buffer');
+
+const buf = Buffer.from('buffer');
+
+console.log(buf.subarray(-6, -1).toString());
+// Prints: buffe
+// (Equivalent to buf.subarray(0, 5).)
+
+console.log(buf.subarray(-6, -2).toString());
+// Prints: buff
+// (Equivalent to buf.subarray(0, 4).)
+
+console.log(buf.subarray(-5, -2).toString());
+// Prints: uff
+// (Equivalent to buf.subarray(1, 4).)
+```
+
+#### `buf.slice([start[, end]])`
+
+
+
+* `start` [`integer`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type) Where the new `Buffer` will start. **Default:** `0`.
+* `end` [`integer`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type) Where the new `Buffer` will end (not inclusive).
+ **Default:** [`buf.length`][].
+* Returns: [`Buffer`](/api/v16/buffer#buffer)
+
+
+
+Deprecated: Use [`buf.subarray`][] instead.
+
+
+
+Returns a new `Buffer` that references the same memory as the original, but
+offset and cropped by the `start` and `end` indices.
+
+This method is not compatible with the `Uint8Array.prototype.slice()`,
+which is a superclass of `Buffer`. To copy the slice, use
+`Uint8Array.prototype.slice()`.
+
+```mjs|cjs
+import { Buffer } from 'node:buffer';
+
+const buf = Buffer.from('buffer');
+
+const copiedBuf = Uint8Array.prototype.slice.call(buf);
+copiedBuf[0]++;
+console.log(copiedBuf.toString());
+// Prints: cuffer
+
+console.log(buf.toString());
+// Prints: buffer
+
+// With buf.slice(), the original buffer is modified.
+const notReallyCopiedBuf = buf.slice();
+notReallyCopiedBuf[0]++;
+console.log(notReallyCopiedBuf.toString());
+// Prints: cuffer
+console.log(buf.toString());
+// Also prints: cuffer (!)
+--------------
+const { Buffer } = require('node:buffer');
+
+const buf = Buffer.from('buffer');
+
+const copiedBuf = Uint8Array.prototype.slice.call(buf);
+copiedBuf[0]++;
+console.log(copiedBuf.toString());
+// Prints: cuffer
+
+console.log(buf.toString());
+// Prints: buffer
+
+// With buf.slice(), the original buffer is modified.
+const notReallyCopiedBuf = buf.slice();
+notReallyCopiedBuf[0]++;
+console.log(notReallyCopiedBuf.toString());
+// Prints: cuffer
+console.log(buf.toString());
+// Also prints: cuffer (!)
+```
+
+#### `buf.swap16()`
+
+
+
+* Returns: [`Buffer`](/api/v16/buffer#buffer) A reference to `buf`.
+
+Interprets `buf` as an array of unsigned 16-bit integers and swaps the
+byte order _in-place_. Throws [`ERR_INVALID_BUFFER_SIZE`][] if [`buf.length`][]
+is not a multiple of 2.
+
+```mjs|cjs
+import { Buffer } from 'node:buffer';
+
+const buf1 = Buffer.from([0x1, 0x2, 0x3, 0x4, 0x5, 0x6, 0x7, 0x8]);
+
+console.log(buf1);
+// Prints:
+
+buf1.swap16();
+
+console.log(buf1);
+// Prints:
+
+const buf2 = Buffer.from([0x1, 0x2, 0x3]);
+
+buf2.swap16();
+// Throws ERR_INVALID_BUFFER_SIZE.
+--------------
+const { Buffer } = require('node:buffer');
+
+const buf1 = Buffer.from([0x1, 0x2, 0x3, 0x4, 0x5, 0x6, 0x7, 0x8]);
+
+console.log(buf1);
+// Prints:
+
+buf1.swap16();
+
+console.log(buf1);
+// Prints:
+
+const buf2 = Buffer.from([0x1, 0x2, 0x3]);
+
+buf2.swap16();
+// Throws ERR_INVALID_BUFFER_SIZE.
+```
+
+One convenient use of `buf.swap16()` is to perform a fast in-place conversion
+between UTF-16 little-endian and UTF-16 big-endian:
+
+```mjs|cjs
+import { Buffer } from 'node:buffer';
+
+const buf = Buffer.from('This is little-endian UTF-16', 'utf16le');
+buf.swap16(); // Convert to big-endian UTF-16 text.
+--------------
+const { Buffer } = require('node:buffer');
+
+const buf = Buffer.from('This is little-endian UTF-16', 'utf16le');
+buf.swap16(); // Convert to big-endian UTF-16 text.
+```
+
+#### `buf.swap32()`
+
+
+
+* Returns: [`Buffer`](/api/v16/buffer#buffer) A reference to `buf`.
+
+Interprets `buf` as an array of unsigned 32-bit integers and swaps the
+byte order _in-place_. Throws [`ERR_INVALID_BUFFER_SIZE`][] if [`buf.length`][]
+is not a multiple of 4.
+
+```mjs|cjs
+import { Buffer } from 'node:buffer';
+
+const buf1 = Buffer.from([0x1, 0x2, 0x3, 0x4, 0x5, 0x6, 0x7, 0x8]);
+
+console.log(buf1);
+// Prints:
+
+buf1.swap32();
+
+console.log(buf1);
+// Prints:
+
+const buf2 = Buffer.from([0x1, 0x2, 0x3]);
+
+buf2.swap32();
+// Throws ERR_INVALID_BUFFER_SIZE.
+--------------
+const { Buffer } = require('node:buffer');
+
+const buf1 = Buffer.from([0x1, 0x2, 0x3, 0x4, 0x5, 0x6, 0x7, 0x8]);
+
+console.log(buf1);
+// Prints:
+
+buf1.swap32();
+
+console.log(buf1);
+// Prints:
+
+const buf2 = Buffer.from([0x1, 0x2, 0x3]);
+
+buf2.swap32();
+// Throws ERR_INVALID_BUFFER_SIZE.
+```
+
+#### `buf.swap64()`
+
+
+
+* Returns: [`Buffer`](/api/v16/buffer#buffer) A reference to `buf`.
+
+Interprets `buf` as an array of 64-bit numbers and swaps byte order _in-place_.
+Throws [`ERR_INVALID_BUFFER_SIZE`][] if [`buf.length`][] is not a multiple of 8.
+
+```mjs|cjs
+import { Buffer } from 'node:buffer';
+
+const buf1 = Buffer.from([0x1, 0x2, 0x3, 0x4, 0x5, 0x6, 0x7, 0x8]);
+
+console.log(buf1);
+// Prints:
+
+buf1.swap64();
+
+console.log(buf1);
+// Prints:
+
+const buf2 = Buffer.from([0x1, 0x2, 0x3]);
+
+buf2.swap64();
+// Throws ERR_INVALID_BUFFER_SIZE.
+--------------
+const { Buffer } = require('node:buffer');
+
+const buf1 = Buffer.from([0x1, 0x2, 0x3, 0x4, 0x5, 0x6, 0x7, 0x8]);
+
+console.log(buf1);
+// Prints:
+
+buf1.swap64();
+
+console.log(buf1);
+// Prints:
+
+const buf2 = Buffer.from([0x1, 0x2, 0x3]);
+
+buf2.swap64();
+// Throws ERR_INVALID_BUFFER_SIZE.
+```
+
+#### `buf.toJSON()`
+
+
+
+* Returns: [`Object`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object)
+
+Returns a JSON representation of `buf`. [`JSON.stringify()`][] implicitly calls
+this function when stringifying a `Buffer` instance.
+
+`Buffer.from()` accepts objects in the format returned from this method.
+In particular, `Buffer.from(buf.toJSON())` works like `Buffer.from(buf)`.
+
+```mjs|cjs
+import { Buffer } from 'node:buffer';
+
+const buf = Buffer.from([0x1, 0x2, 0x3, 0x4, 0x5]);
+const json = JSON.stringify(buf);
+
+console.log(json);
+// Prints: {"type":"Buffer","data":[1,2,3,4,5]}
+
+const copy = JSON.parse(json, (key, value) => {
+ return value && value.type === 'Buffer' ?
+ Buffer.from(value) :
+ value;
+});
+
+console.log(copy);
+// Prints:
+--------------
+const { Buffer } = require('node:buffer');
+
+const buf = Buffer.from([0x1, 0x2, 0x3, 0x4, 0x5]);
+const json = JSON.stringify(buf);
+
+console.log(json);
+// Prints: {"type":"Buffer","data":[1,2,3,4,5]}
+
+const copy = JSON.parse(json, (key, value) => {
+ return value && value.type === 'Buffer' ?
+ Buffer.from(value) :
+ value;
+});
+
+console.log(copy);
+// Prints:
+```
+
+#### `buf.toString([encoding[, start[, end]]])`
+
+
+
+* `encoding` [`string`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type) The character encoding to use. **Default:** `'utf8'`.
+* `start` [`integer`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type) The byte offset to start decoding at. **Default:** `0`.
+* `end` [`integer`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type) The byte offset to stop decoding at (not inclusive).
+ **Default:** [`buf.length`][].
+* Returns: [`string`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type)
+
+Decodes `buf` to a string according to the specified character encoding in
+`encoding`. `start` and `end` may be passed to decode only a subset of `buf`.
+
+If `encoding` is `'utf8'` and a byte sequence in the input is not valid UTF-8,
+then each invalid byte is replaced with the replacement character `U+FFFD`.
+
+The maximum length of a string instance (in UTF-16 code units) is available
+as [`buffer.constants.MAX_STRING_LENGTH`][].
+
+```mjs|cjs
+import { Buffer } from 'node:buffer';
+
+const buf1 = Buffer.allocUnsafe(26);
+
+for (let i = 0; i < 26; i++) {
+ // 97 is the decimal ASCII value for 'a'.
+ buf1[i] = i + 97;
+}
+
+console.log(buf1.toString('utf8'));
+// Prints: abcdefghijklmnopqrstuvwxyz
+console.log(buf1.toString('utf8', 0, 5));
+// Prints: abcde
+
+const buf2 = Buffer.from('tést');
+
+console.log(buf2.toString('hex'));
+// Prints: 74c3a97374
+console.log(buf2.toString('utf8', 0, 3));
+// Prints: té
+console.log(buf2.toString(undefined, 0, 3));
+// Prints: té
+--------------
+const { Buffer } = require('node:buffer');
+
+const buf1 = Buffer.allocUnsafe(26);
+
+for (let i = 0; i < 26; i++) {
+ // 97 is the decimal ASCII value for 'a'.
+ buf1[i] = i + 97;
+}
+
+console.log(buf1.toString('utf8'));
+// Prints: abcdefghijklmnopqrstuvwxyz
+console.log(buf1.toString('utf8', 0, 5));
+// Prints: abcde
+
+const buf2 = Buffer.from('tést');
+
+console.log(buf2.toString('hex'));
+// Prints: 74c3a97374
+console.log(buf2.toString('utf8', 0, 3));
+// Prints: té
+console.log(buf2.toString(undefined, 0, 3));
+// Prints: té
+```
+
+#### `buf.values()`
+
+
+
+* Returns: [`Iterator`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Iteration_protocols#The_iterator_protocol)
+
+Creates and returns an [iterator][] for `buf` values (bytes). This function is
+called automatically when a `Buffer` is used in a `for..of` statement.
+
+```mjs|cjs
+import { Buffer } from 'node:buffer';
+
+const buf = Buffer.from('buffer');
+
+for (const value of buf.values()) {
+ console.log(value);
+}
+// Prints:
+// 98
+// 117
+// 102
+// 102
+// 101
+// 114
+
+for (const value of buf) {
+ console.log(value);
+}
+// Prints:
+// 98
+// 117
+// 102
+// 102
+// 101
+// 114
+--------------
+const { Buffer } = require('node:buffer');
+
+const buf = Buffer.from('buffer');
+
+for (const value of buf.values()) {
+ console.log(value);
+}
+// Prints:
+// 98
+// 117
+// 102
+// 102
+// 101
+// 114
+
+for (const value of buf) {
+ console.log(value);
+}
+// Prints:
+// 98
+// 117
+// 102
+// 102
+// 101
+// 114
+```
+
+#### `buf.write(string[, offset[, length]][, encoding])`
+
+
+
+* `string` [`string`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type) String to write to `buf`.
+* `offset` [`integer`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type) Number of bytes to skip before starting to write `string`.
+ **Default:** `0`.
+* `length` [`integer`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type) Maximum number of bytes to write (written bytes will not
+ exceed `buf.length - offset`). **Default:** `buf.length - offset`.
+* `encoding` [`string`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type) The character encoding of `string`. **Default:** `'utf8'`.
+* Returns: [`integer`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type) Number of bytes written.
+
+Writes `string` to `buf` at `offset` according to the character encoding in
+`encoding`. The `length` parameter is the number of bytes to write. If `buf` did
+not contain enough space to fit the entire string, only part of `string` will be
+written. However, partially encoded characters will not be written.
+
+```mjs|cjs
+import { Buffer } from 'node:buffer';
+
+const buf = Buffer.alloc(256);
+
+const len = buf.write('\u00bd + \u00bc = \u00be', 0);
+
+console.log(`${len} bytes: ${buf.toString('utf8', 0, len)}`);
+// Prints: 12 bytes: ½ + ¼ = ¾
+
+const buffer = Buffer.alloc(10);
+
+const length = buffer.write('abcd', 8);
+
+console.log(`${length} bytes: ${buffer.toString('utf8', 8, 10)}`);
+// Prints: 2 bytes : ab
+--------------
+const { Buffer } = require('node:buffer');
+
+const buf = Buffer.alloc(256);
+
+const len = buf.write('\u00bd + \u00bc = \u00be', 0);
+
+console.log(`${len} bytes: ${buf.toString('utf8', 0, len)}`);
+// Prints: 12 bytes: ½ + ¼ = ¾
+
+const buffer = Buffer.alloc(10);
+
+const length = buffer.write('abcd', 8);
+
+console.log(`${length} bytes: ${buffer.toString('utf8', 8, 10)}`);
+// Prints: 2 bytes : ab
+```
+
+#### `buf.writeBigInt64BE(value[, offset])`
+
+
+
+* `value` [`bigint`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/BigInt) Number to be written to `buf`.
+* `offset` [`integer`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type) Number of bytes to skip before starting to write. Must
+ satisfy: `0 <= offset <= buf.length - 8`. **Default:** `0`.
+* Returns: [`integer`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type) `offset` plus the number of bytes written.
+
+Writes `value` to `buf` at the specified `offset` as big-endian.
+
+`value` is interpreted and written as a two's complement signed integer.
+
+```mjs|cjs
+import { Buffer } from 'node:buffer';
+
+const buf = Buffer.allocUnsafe(8);
+
+buf.writeBigInt64BE(0x0102030405060708n, 0);
+
+console.log(buf);
+// Prints:
+--------------
+const { Buffer } = require('node:buffer');
+
+const buf = Buffer.allocUnsafe(8);
+
+buf.writeBigInt64BE(0x0102030405060708n, 0);
+
+console.log(buf);
+// Prints:
+```
+
+#### `buf.writeBigInt64LE(value[, offset])`
+
+
+
+* `value` [`bigint`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/BigInt) Number to be written to `buf`.
+* `offset` [`integer`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type) Number of bytes to skip before starting to write. Must
+ satisfy: `0 <= offset <= buf.length - 8`. **Default:** `0`.
+* Returns: [`integer`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type) `offset` plus the number of bytes written.
+
+Writes `value` to `buf` at the specified `offset` as little-endian.
+
+`value` is interpreted and written as a two's complement signed integer.
+
+```mjs|cjs
+import { Buffer } from 'node:buffer';
+
+const buf = Buffer.allocUnsafe(8);
+
+buf.writeBigInt64LE(0x0102030405060708n, 0);
+
+console.log(buf);
+// Prints:
+--------------
+const { Buffer } = require('node:buffer');
+
+const buf = Buffer.allocUnsafe(8);
+
+buf.writeBigInt64LE(0x0102030405060708n, 0);
+
+console.log(buf);
+// Prints:
+```
+
+#### `buf.writeBigUInt64BE(value[, offset])`
+
+
+
+* `value` [`bigint`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/BigInt) Number to be written to `buf`.
+* `offset` [`integer`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type) Number of bytes to skip before starting to write. Must
+ satisfy: `0 <= offset <= buf.length - 8`. **Default:** `0`.
+* Returns: [`integer`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type) `offset` plus the number of bytes written.
+
+Writes `value` to `buf` at the specified `offset` as big-endian.
+
+This function is also available under the `writeBigUint64BE` alias.
+
+```mjs|cjs
+import { Buffer } from 'node:buffer';
+
+const buf = Buffer.allocUnsafe(8);
+
+buf.writeBigUInt64BE(0xdecafafecacefaden, 0);
+
+console.log(buf);
+// Prints:
+--------------
+const { Buffer } = require('node:buffer');
+
+const buf = Buffer.allocUnsafe(8);
+
+buf.writeBigUInt64BE(0xdecafafecacefaden, 0);
+
+console.log(buf);
+// Prints:
+```
+
+#### `buf.writeBigUInt64LE(value[, offset])`
+
+
+
+* `value` [`bigint`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/BigInt) Number to be written to `buf`.
+* `offset` [`integer`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type) Number of bytes to skip before starting to write. Must
+ satisfy: `0 <= offset <= buf.length - 8`. **Default:** `0`.
+* Returns: [`integer`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type) `offset` plus the number of bytes written.
+
+Writes `value` to `buf` at the specified `offset` as little-endian
+
+```mjs|cjs
+import { Buffer } from 'node:buffer';
+
+const buf = Buffer.allocUnsafe(8);
+
+buf.writeBigUInt64LE(0xdecafafecacefaden, 0);
+
+console.log(buf);
+// Prints:
+--------------
+const { Buffer } = require('node:buffer');
+
+const buf = Buffer.allocUnsafe(8);
+
+buf.writeBigUInt64LE(0xdecafafecacefaden, 0);
+
+console.log(buf);
+// Prints:
+```
+
+This function is also available under the `writeBigUint64LE` alias.
+
+#### `buf.writeDoubleBE(value[, offset])`
+
+
+
+* `value` [`number`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type) Number to be written to `buf`.
+* `offset` [`integer`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type) Number of bytes to skip before starting to write. Must
+ satisfy `0 <= offset <= buf.length - 8`. **Default:** `0`.
+* Returns: [`integer`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type) `offset` plus the number of bytes written.
+
+Writes `value` to `buf` at the specified `offset` as big-endian. The `value`
+must be a JavaScript number. Behavior is undefined when `value` is anything
+other than a JavaScript number.
+
+```mjs|cjs
+import { Buffer } from 'node:buffer';
+
+const buf = Buffer.allocUnsafe(8);
+
+buf.writeDoubleBE(123.456, 0);
+
+console.log(buf);
+// Prints:
+--------------
+const { Buffer } = require('node:buffer');
+
+const buf = Buffer.allocUnsafe(8);
+
+buf.writeDoubleBE(123.456, 0);
+
+console.log(buf);
+// Prints:
+```
+
+#### `buf.writeDoubleLE(value[, offset])`
+
+
+
+* `value` [`number`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type) Number to be written to `buf`.
+* `offset` [`integer`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type) Number of bytes to skip before starting to write. Must
+ satisfy `0 <= offset <= buf.length - 8`. **Default:** `0`.
+* Returns: [`integer`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type) `offset` plus the number of bytes written.
+
+Writes `value` to `buf` at the specified `offset` as little-endian. The `value`
+must be a JavaScript number. Behavior is undefined when `value` is anything
+other than a JavaScript number.
+
+```mjs|cjs
+import { Buffer } from 'node:buffer';
+
+const buf = Buffer.allocUnsafe(8);
+
+buf.writeDoubleLE(123.456, 0);
+
+console.log(buf);
+// Prints:
+--------------
+const { Buffer } = require('node:buffer');
+
+const buf = Buffer.allocUnsafe(8);
+
+buf.writeDoubleLE(123.456, 0);
+
+console.log(buf);
+// Prints:
+```
+
+#### `buf.writeFloatBE(value[, offset])`
+
+
+
+* `value` [`number`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type) Number to be written to `buf`.
+* `offset` [`integer`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type) Number of bytes to skip before starting to write. Must
+ satisfy `0 <= offset <= buf.length - 4`. **Default:** `0`.
+* Returns: [`integer`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type) `offset` plus the number of bytes written.
+
+Writes `value` to `buf` at the specified `offset` as big-endian. Behavior is
+undefined when `value` is anything other than a JavaScript number.
+
+```mjs|cjs
+import { Buffer } from 'node:buffer';
+
+const buf = Buffer.allocUnsafe(4);
+
+buf.writeFloatBE(0xcafebabe, 0);
+
+console.log(buf);
+// Prints:
+--------------
+const { Buffer } = require('node:buffer');
+
+const buf = Buffer.allocUnsafe(4);
+
+buf.writeFloatBE(0xcafebabe, 0);
+
+console.log(buf);
+// Prints:
+```
+
+#### `buf.writeFloatLE(value[, offset])`
+
+
+
+* `value` [`number`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type) Number to be written to `buf`.
+* `offset` [`integer`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type) Number of bytes to skip before starting to write. Must
+ satisfy `0 <= offset <= buf.length - 4`. **Default:** `0`.
+* Returns: [`integer`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type) `offset` plus the number of bytes written.
+
+Writes `value` to `buf` at the specified `offset` as little-endian. Behavior is
+undefined when `value` is anything other than a JavaScript number.
+
+```mjs|cjs
+import { Buffer } from 'node:buffer';
+
+const buf = Buffer.allocUnsafe(4);
+
+buf.writeFloatLE(0xcafebabe, 0);
+
+console.log(buf);
+// Prints:
+--------------
+const { Buffer } = require('node:buffer');
+
+const buf = Buffer.allocUnsafe(4);
+
+buf.writeFloatLE(0xcafebabe, 0);
+
+console.log(buf);
+// Prints:
+```
+
+#### `buf.writeInt8(value[, offset])`
+
+
+
+* `value` [`integer`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type) Number to be written to `buf`.
+* `offset` [`integer`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type) Number of bytes to skip before starting to write. Must
+ satisfy `0 <= offset <= buf.length - 1`. **Default:** `0`.
+* Returns: [`integer`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type) `offset` plus the number of bytes written.
+
+Writes `value` to `buf` at the specified `offset`. `value` must be a valid
+signed 8-bit integer. Behavior is undefined when `value` is anything other than
+a signed 8-bit integer.
+
+`value` is interpreted and written as a two's complement signed integer.
+
+```mjs|cjs
+import { Buffer } from 'node:buffer';
+
+const buf = Buffer.allocUnsafe(2);
+
+buf.writeInt8(2, 0);
+buf.writeInt8(-2, 1);
+
+console.log(buf);
+// Prints:
+--------------
+const { Buffer } = require('node:buffer');
+
+const buf = Buffer.allocUnsafe(2);
+
+buf.writeInt8(2, 0);
+buf.writeInt8(-2, 1);
+
+console.log(buf);
+// Prints:
+```
+
+#### `buf.writeInt16BE(value[, offset])`
+
+
+
+* `value` [`integer`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type) Number to be written to `buf`.
+* `offset` [`integer`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type) Number of bytes to skip before starting to write. Must
+ satisfy `0 <= offset <= buf.length - 2`. **Default:** `0`.
+* Returns: [`integer`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type) `offset` plus the number of bytes written.
+
+Writes `value` to `buf` at the specified `offset` as big-endian. The `value`
+must be a valid signed 16-bit integer. Behavior is undefined when `value` is
+anything other than a signed 16-bit integer.
+
+The `value` is interpreted and written as a two's complement signed integer.
+
+```mjs|cjs
+import { Buffer } from 'node:buffer';
+
+const buf = Buffer.allocUnsafe(2);
+
+buf.writeInt16BE(0x0102, 0);
+
+console.log(buf);
+// Prints:
+--------------
+const { Buffer } = require('node:buffer');
+
+const buf = Buffer.allocUnsafe(2);
+
+buf.writeInt16BE(0x0102, 0);
+
+console.log(buf);
+// Prints:
+```
+
+#### `buf.writeInt16LE(value[, offset])`
+
+
+
+* `value` [`integer`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type) Number to be written to `buf`.
+* `offset` [`integer`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type) Number of bytes to skip before starting to write. Must
+ satisfy `0 <= offset <= buf.length - 2`. **Default:** `0`.
+* Returns: [`integer`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type) `offset` plus the number of bytes written.
+
+Writes `value` to `buf` at the specified `offset` as little-endian. The `value`
+must be a valid signed 16-bit integer. Behavior is undefined when `value` is
+anything other than a signed 16-bit integer.
+
+The `value` is interpreted and written as a two's complement signed integer.
+
+```mjs|cjs
+import { Buffer } from 'node:buffer';
+
+const buf = Buffer.allocUnsafe(2);
+
+buf.writeInt16LE(0x0304, 0);
+
+console.log(buf);
+// Prints:
+--------------
+const { Buffer } = require('node:buffer');
+
+const buf = Buffer.allocUnsafe(2);
+
+buf.writeInt16LE(0x0304, 0);
+
+console.log(buf);
+// Prints:
+```
+
+#### `buf.writeInt32BE(value[, offset])`
+
+
+
+* `value` [`integer`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type) Number to be written to `buf`.
+* `offset` [`integer`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type) Number of bytes to skip before starting to write. Must
+ satisfy `0 <= offset <= buf.length - 4`. **Default:** `0`.
+* Returns: [`integer`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type) `offset` plus the number of bytes written.
+
+Writes `value` to `buf` at the specified `offset` as big-endian. The `value`
+must be a valid signed 32-bit integer. Behavior is undefined when `value` is
+anything other than a signed 32-bit integer.
+
+The `value` is interpreted and written as a two's complement signed integer.
+
+```mjs|cjs
+import { Buffer } from 'node:buffer';
+
+const buf = Buffer.allocUnsafe(4);
+
+buf.writeInt32BE(0x01020304, 0);
+
+console.log(buf);
+// Prints:
+--------------
+const { Buffer } = require('node:buffer');
+
+const buf = Buffer.allocUnsafe(4);
+
+buf.writeInt32BE(0x01020304, 0);
+
+console.log(buf);
+// Prints:
+```
+
+#### `buf.writeInt32LE(value[, offset])`
+
+
+
+* `value` [`integer`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type) Number to be written to `buf`.
+* `offset` [`integer`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type) Number of bytes to skip before starting to write. Must
+ satisfy `0 <= offset <= buf.length - 4`. **Default:** `0`.
+* Returns: [`integer`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type) `offset` plus the number of bytes written.
+
+Writes `value` to `buf` at the specified `offset` as little-endian. The `value`
+must be a valid signed 32-bit integer. Behavior is undefined when `value` is
+anything other than a signed 32-bit integer.
+
+The `value` is interpreted and written as a two's complement signed integer.
+
+```mjs|cjs
+import { Buffer } from 'node:buffer';
+
+const buf = Buffer.allocUnsafe(4);
+
+buf.writeInt32LE(0x05060708, 0);
+
+console.log(buf);
+// Prints:
+--------------
+const { Buffer } = require('node:buffer');
+
+const buf = Buffer.allocUnsafe(4);
+
+buf.writeInt32LE(0x05060708, 0);
+
+console.log(buf);
+// Prints:
+```
+
+#### `buf.writeIntBE(value, offset, byteLength)`
+
+
+
+* `value` [`integer`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type) Number to be written to `buf`.
+* `offset` [`integer`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type) Number of bytes to skip before starting to write. Must
+ satisfy `0 <= offset <= buf.length - byteLength`.
+* `byteLength` [`integer`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type) Number of bytes to write. Must satisfy
+ `0 < byteLength <= 6`.
+* Returns: [`integer`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type) `offset` plus the number of bytes written.
+
+Writes `byteLength` bytes of `value` to `buf` at the specified `offset`
+as big-endian. Supports up to 48 bits of accuracy. Behavior is undefined when
+`value` is anything other than a signed integer.
+
+```mjs|cjs
+import { Buffer } from 'node:buffer';
+
+const buf = Buffer.allocUnsafe(6);
+
+buf.writeIntBE(0x1234567890ab, 0, 6);
+
+console.log(buf);
+// Prints:
+--------------
+const { Buffer } = require('node:buffer');
+
+const buf = Buffer.allocUnsafe(6);
+
+buf.writeIntBE(0x1234567890ab, 0, 6);
+
+console.log(buf);
+// Prints:
+```
+
+#### `buf.writeIntLE(value, offset, byteLength)`
+
+
+
+* `value` [`integer`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type) Number to be written to `buf`.
+* `offset` [`integer`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type) Number of bytes to skip before starting to write. Must
+ satisfy `0 <= offset <= buf.length - byteLength`.
+* `byteLength` [`integer`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type) Number of bytes to write. Must satisfy
+ `0 < byteLength <= 6`.
+* Returns: [`integer`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type) `offset` plus the number of bytes written.
+
+Writes `byteLength` bytes of `value` to `buf` at the specified `offset`
+as little-endian. Supports up to 48 bits of accuracy. Behavior is undefined
+when `value` is anything other than a signed integer.
+
+```mjs|cjs
+import { Buffer } from 'node:buffer';
+
+const buf = Buffer.allocUnsafe(6);
+
+buf.writeIntLE(0x1234567890ab, 0, 6);
+
+console.log(buf);
+// Prints:
+--------------
+const { Buffer } = require('node:buffer');
+
+const buf = Buffer.allocUnsafe(6);
+
+buf.writeIntLE(0x1234567890ab, 0, 6);
+
+console.log(buf);
+// Prints:
+```
+
+#### `buf.writeUInt8(value[, offset])`
+
+
+
+* `value` [`integer`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type) Number to be written to `buf`.
+* `offset` [`integer`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type) Number of bytes to skip before starting to write. Must
+ satisfy `0 <= offset <= buf.length - 1`. **Default:** `0`.
+* Returns: [`integer`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type) `offset` plus the number of bytes written.
+
+Writes `value` to `buf` at the specified `offset`. `value` must be a
+valid unsigned 8-bit integer. Behavior is undefined when `value` is anything
+other than an unsigned 8-bit integer.
+
+This function is also available under the `writeUint8` alias.
+
+```mjs|cjs
+import { Buffer } from 'node:buffer';
+
+const buf = Buffer.allocUnsafe(4);
+
+buf.writeUInt8(0x3, 0);
+buf.writeUInt8(0x4, 1);
+buf.writeUInt8(0x23, 2);
+buf.writeUInt8(0x42, 3);
+
+console.log(buf);
+// Prints:
+--------------
+const { Buffer } = require('node:buffer');
+
+const buf = Buffer.allocUnsafe(4);
+
+buf.writeUInt8(0x3, 0);
+buf.writeUInt8(0x4, 1);
+buf.writeUInt8(0x23, 2);
+buf.writeUInt8(0x42, 3);
+
+console.log(buf);
+// Prints:
+```
+
+#### `buf.writeUInt16BE(value[, offset])`
+
+
+
+* `value` [`integer`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type) Number to be written to `buf`.
+* `offset` [`integer`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type) Number of bytes to skip before starting to write. Must
+ satisfy `0 <= offset <= buf.length - 2`. **Default:** `0`.
+* Returns: [`integer`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type) `offset` plus the number of bytes written.
+
+Writes `value` to `buf` at the specified `offset` as big-endian. The `value`
+must be a valid unsigned 16-bit integer. Behavior is undefined when `value`
+is anything other than an unsigned 16-bit integer.
+
+This function is also available under the `writeUint16BE` alias.
+
+```mjs|cjs
+import { Buffer } from 'node:buffer';
+
+const buf = Buffer.allocUnsafe(4);
+
+buf.writeUInt16BE(0xdead, 0);
+buf.writeUInt16BE(0xbeef, 2);
+
+console.log(buf);
+// Prints:
+--------------
+const { Buffer } = require('node:buffer');
+
+const buf = Buffer.allocUnsafe(4);
+
+buf.writeUInt16BE(0xdead, 0);
+buf.writeUInt16BE(0xbeef, 2);
+
+console.log(buf);
+// Prints:
+```
+
+#### `buf.writeUInt16LE(value[, offset])`
+
+
+
+* `value` [`integer`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type) Number to be written to `buf`.
+* `offset` [`integer`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type) Number of bytes to skip before starting to write. Must
+ satisfy `0 <= offset <= buf.length - 2`. **Default:** `0`.
+* Returns: [`integer`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type) `offset` plus the number of bytes written.
+
+Writes `value` to `buf` at the specified `offset` as little-endian. The `value`
+must be a valid unsigned 16-bit integer. Behavior is undefined when `value` is
+anything other than an unsigned 16-bit integer.
+
+This function is also available under the `writeUint16LE` alias.
+
+```mjs|cjs
+import { Buffer } from 'node:buffer';
+
+const buf = Buffer.allocUnsafe(4);
+
+buf.writeUInt16LE(0xdead, 0);
+buf.writeUInt16LE(0xbeef, 2);
+
+console.log(buf);
+// Prints:
+--------------
+const { Buffer } = require('node:buffer');
+
+const buf = Buffer.allocUnsafe(4);
+
+buf.writeUInt16LE(0xdead, 0);
+buf.writeUInt16LE(0xbeef, 2);
+
+console.log(buf);
+// Prints:
+```
+
+#### `buf.writeUInt32BE(value[, offset])`
+
+
+
+* `value` [`integer`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type) Number to be written to `buf`.
+* `offset` [`integer`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type) Number of bytes to skip before starting to write. Must
+ satisfy `0 <= offset <= buf.length - 4`. **Default:** `0`.
+* Returns: [`integer`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type) `offset` plus the number of bytes written.
+
+Writes `value` to `buf` at the specified `offset` as big-endian. The `value`
+must be a valid unsigned 32-bit integer. Behavior is undefined when `value`
+is anything other than an unsigned 32-bit integer.
+
+This function is also available under the `writeUint32BE` alias.
+
+```mjs|cjs
+import { Buffer } from 'node:buffer';
+
+const buf = Buffer.allocUnsafe(4);
+
+buf.writeUInt32BE(0xfeedface, 0);
+
+console.log(buf);
+// Prints:
+--------------
+const { Buffer } = require('node:buffer');
+
+const buf = Buffer.allocUnsafe(4);
+
+buf.writeUInt32BE(0xfeedface, 0);
+
+console.log(buf);
+// Prints:
+```
+
+#### `buf.writeUInt32LE(value[, offset])`
+
+
+
+* `value` [`integer`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type) Number to be written to `buf`.
+* `offset` [`integer`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type) Number of bytes to skip before starting to write. Must
+ satisfy `0 <= offset <= buf.length - 4`. **Default:** `0`.
+* Returns: [`integer`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type) `offset` plus the number of bytes written.
+
+Writes `value` to `buf` at the specified `offset` as little-endian. The `value`
+must be a valid unsigned 32-bit integer. Behavior is undefined when `value` is
+anything other than an unsigned 32-bit integer.
+
+This function is also available under the `writeUint32LE` alias.
+
+```mjs|cjs
+import { Buffer } from 'node:buffer';
+
+const buf = Buffer.allocUnsafe(4);
+
+buf.writeUInt32LE(0xfeedface, 0);
+
+console.log(buf);
+// Prints:
+--------------
+const { Buffer } = require('node:buffer');
+
+const buf = Buffer.allocUnsafe(4);
+
+buf.writeUInt32LE(0xfeedface, 0);
+
+console.log(buf);
+// Prints:
+```
+
+#### `buf.writeUIntBE(value, offset, byteLength)`
+
+
+
+* `value` [`integer`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type) Number to be written to `buf`.
+* `offset` [`integer`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type) Number of bytes to skip before starting to write. Must
+ satisfy `0 <= offset <= buf.length - byteLength`.
+* `byteLength` [`integer`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type) Number of bytes to write. Must satisfy
+ `0 < byteLength <= 6`.
+* Returns: [`integer`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type) `offset` plus the number of bytes written.
+
+Writes `byteLength` bytes of `value` to `buf` at the specified `offset`
+as big-endian. Supports up to 48 bits of accuracy. Behavior is undefined
+when `value` is anything other than an unsigned integer.
+
+This function is also available under the `writeUintBE` alias.
+
+```mjs|cjs
+import { Buffer } from 'node:buffer';
+
+const buf = Buffer.allocUnsafe(6);
+
+buf.writeUIntBE(0x1234567890ab, 0, 6);
+
+console.log(buf);
+// Prints:
+--------------
+const { Buffer } = require('node:buffer');
+
+const buf = Buffer.allocUnsafe(6);
+
+buf.writeUIntBE(0x1234567890ab, 0, 6);
+
+console.log(buf);
+// Prints:
+```
+
+#### `buf.writeUIntLE(value, offset, byteLength)`
+
+
+
+* `value` [`integer`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type) Number to be written to `buf`.
+* `offset` [`integer`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type) Number of bytes to skip before starting to write. Must
+ satisfy `0 <= offset <= buf.length - byteLength`.
+* `byteLength` [`integer`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type) Number of bytes to write. Must satisfy
+ `0 < byteLength <= 6`.
+* Returns: [`integer`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type) `offset` plus the number of bytes written.
+
+Writes `byteLength` bytes of `value` to `buf` at the specified `offset`
+as little-endian. Supports up to 48 bits of accuracy. Behavior is undefined
+when `value` is anything other than an unsigned integer.
+
+This function is also available under the `writeUintLE` alias.
+
+```mjs|cjs
+import { Buffer } from 'node:buffer';
+
+const buf = Buffer.allocUnsafe(6);
+
+buf.writeUIntLE(0x1234567890ab, 0, 6);
+
+console.log(buf);
+// Prints:
+--------------
+const { Buffer } = require('node:buffer');
+
+const buf = Buffer.allocUnsafe(6);
+
+buf.writeUIntLE(0x1234567890ab, 0, 6);
+
+console.log(buf);
+// Prints:
+```
+
+#### `new Buffer(array)`
+
+
+
+
+
+Deprecated: Use [`Buffer.from(array)`][] instead.
+
+
+
+* `array` integer\[] An array of bytes to copy from.
+
+See [`Buffer.from(array)`][].
+
+#### `new Buffer(arrayBuffer[, byteOffset[, length]])`
+
+
+
+
+
+Deprecated: Use [`Buffer.from(arrayBuffer[, byteOffset[, length]])`][`Buffer.from(arrayBuf)`] instead.
+
+
+
+* `arrayBuffer` [`ArrayBuffer`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/ArrayBuffer) | [`SharedArrayBuffer`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/SharedArrayBuffer) An [`ArrayBuffer`][],
+ [`SharedArrayBuffer`][] or the `.buffer` property of a [`TypedArray`][].
+* `byteOffset` [`integer`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type) Index of first byte to expose. **Default:** `0`.
+* `length` [`integer`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type) Number of bytes to expose.
+ **Default:** `arrayBuffer.byteLength - byteOffset`.
+
+See
+[`Buffer.from(arrayBuffer[, byteOffset[, length]])`][`Buffer.from(arrayBuf)`].
+
+#### `new Buffer(buffer)`
+
+
+
+
+
+Deprecated: Use [`Buffer.from(buffer)`][] instead.
+
+
+
+* `buffer` [`Buffer`](/api/v16/buffer#buffer) | [`Uint8Array`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Uint8Array) An existing `Buffer` or [`Uint8Array`][] from
+ which to copy data.
+
+See [`Buffer.from(buffer)`][].
+
+#### `new Buffer(size)`
+
+
+
+
+
+Deprecated: Use [`Buffer.alloc()`][] instead (also see [`Buffer.allocUnsafe()`][]).
+
+
+
+* `size` [`integer`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type) The desired length of the new `Buffer`.
+
+See [`Buffer.alloc()`][] and [`Buffer.allocUnsafe()`][]. This variant of the
+constructor is equivalent to [`Buffer.alloc()`][].
+
+#### `new Buffer(string[, encoding])`
+
+
+
+
+
+Deprecated: Use [`Buffer.from(string[, encoding])`][`Buffer.from(string)`] instead.
+
+
+
+* `string` [`string`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type) String to encode.
+* `encoding` [`string`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type) The encoding of `string`. **Default:** `'utf8'`.
+
+See [`Buffer.from(string[, encoding])`][`Buffer.from(string)`].
+
+### `node:buffer` module APIs
+
+While, the `Buffer` object is available as a global, there are additional
+`Buffer`-related APIs that are available only via the `node:buffer` module
+accessed using `require('node:buffer')`.
+
+#### `buffer.atob(data)`
+
+
+
+
+
+Legacy. Use `Buffer.from(data, 'base64')` instead.
+
+
+
+* `data` [`any`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Data_types) The Base64-encoded input string.
+
+Decodes a string of Base64-encoded data into bytes, and encodes those bytes
+into a string using Latin-1 (ISO-8859-1).
+
+The `data` may be any JavaScript-value that can be coerced into a string.
+
+**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 `Buffer.from(str, 'base64')` and
+`buf.toString('base64')`.**
+
+#### `buffer.btoa(data)`
+
+
+
+
+
+Legacy. Use `buf.toString('base64')` instead.
+
+
+
+* `data` [`any`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Data_types) An ASCII (Latin1) string.
+
+Decodes a string into bytes using Latin-1 (ISO-8859), and encodes those bytes
+into a string using Base64.
+
+The `data` may be any JavaScript-value that can be coerced into a string.
+
+**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 `Buffer.from(str, 'base64')` and
+`buf.toString('base64')`.**
+
+#### `buffer.INSPECT_MAX_BYTES`
+
+
+
+* [`integer`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type) **Default:** `50`
+
+Returns the maximum number of bytes that will be returned when
+`buf.inspect()` is called. This can be overridden by user modules. See
+[`util.inspect()`][] for more details on `buf.inspect()` behavior.
+
+#### `buffer.kMaxLength`
+
+
+
+* [`integer`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type) The largest size allowed for a single `Buffer` instance.
+
+An alias for [`buffer.constants.MAX_LENGTH`][].
+
+#### `buffer.kStringMaxLength`
+
+
+
+* [`integer`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type) The largest length allowed for a single `string` instance.
+
+An alias for [`buffer.constants.MAX_STRING_LENGTH`][].
+
+#### `buffer.resolveObjectURL(id)`
+
+
+
+
+
+Experimental
+
+
+
+* `id` [`string`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type) A `'blob:nodedata:...` URL string returned by a prior call to
+ `URL.createObjectURL()`.
+* Returns: [`Blob`](/api/v16/buffer#blob)
+
+Resolves a `'blob:nodedata:...'` an associated [`Blob`](/api/v16/buffer#blob) object registered using
+a prior call to `URL.createObjectURL()`.
+
+#### `buffer.transcode(source, fromEnc, toEnc)`
+
+
+
+* `source` [`Buffer`](/api/v16/buffer#buffer) | [`Uint8Array`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Uint8Array) A `Buffer` or `Uint8Array` instance.
+* `fromEnc` [`string`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type) The current encoding.
+* `toEnc` [`string`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type) To target encoding.
+* Returns: [`Buffer`](/api/v16/buffer#buffer)
+
+Re-encodes the given `Buffer` or `Uint8Array` instance from one character
+encoding to another. Returns a new `Buffer` instance.
+
+Throws if the `fromEnc` or `toEnc` specify invalid character encodings or if
+conversion from `fromEnc` to `toEnc` is not permitted.
+
+Encodings supported by `buffer.transcode()` are: `'ascii'`, `'utf8'`,
+`'utf16le'`, `'ucs2'`, `'latin1'`, and `'binary'`.
+
+The transcoding process will use substitution characters if a given byte
+sequence cannot be adequately represented in the target encoding. For instance:
+
+```mjs|cjs
+import { Buffer, transcode } from 'node:buffer';
+
+const newBuf = transcode(Buffer.from('€'), 'utf8', 'ascii');
+console.log(newBuf.toString('ascii'));
+// Prints: '?'
+--------------
+const { Buffer, transcode } = require('node:buffer');
+
+const newBuf = transcode(Buffer.from('€'), 'utf8', 'ascii');
+console.log(newBuf.toString('ascii'));
+// Prints: '?'
+```
+
+Because the Euro (`€`) sign is not representable in US-ASCII, it is replaced
+with `?` in the transcoded `Buffer`.
+
+#### `SlowBuffer`
+
+
+
+
+
+Deprecated: Use [`Buffer.allocUnsafeSlow()`][] instead.
+
+
+
+See [`Buffer.allocUnsafeSlow()`][]. This was never a class in the sense that
+the constructor always returned a `Buffer` instance, rather than a `SlowBuffer`
+instance.
+
+##### `new SlowBuffer(size)`
+
+
+
+
+
+Deprecated: Use [`Buffer.allocUnsafeSlow()`][] instead.
+
+
+
+* `size` [`integer`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type) The desired length of the new `SlowBuffer`.
+
+See [`Buffer.allocUnsafeSlow()`][].
+
+#### Buffer constants
+
+
+
+##### `buffer.constants.MAX_LENGTH`
+
+32 on 64-bit architectures."},{"version":"v14.0.0","pr-url":"https://github.com/nodejs/node/pull/32116","description":"Value is changed from 231 - 1 to 232 - 1 on 64-bit architectures."}],"update":{"type":"added","version":["v8.2.0"]}}} />
+
+* [`integer`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type) The largest size allowed for a single `Buffer` instance.
+
+On 32-bit architectures, this value currently is 230 - 1 (about 1
+GiB).
+
+On 64-bit architectures, this value currently is 232 (about 4 GiB).
+
+It reflects [`v8::TypedArray::kMaxLength`][] under the hood.
+
+This value is also available as [`buffer.kMaxLength`][].
+
+##### `buffer.constants.MAX_STRING_LENGTH`
+
+
+
+* [`integer`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type) The largest length allowed for a single `string` instance.
+
+Represents the largest `length` that a `string` primitive can have, counted
+in UTF-16 code units.
+
+This value may depend on the JS engine that is being used.
+
+### `Buffer.from()`, `Buffer.alloc()`, and `Buffer.allocUnsafe()`
+
+In versions of Node.js prior to 6.0.0, `Buffer` instances were created using the
+`Buffer` constructor function, which allocates the returned `Buffer`
+differently based on what arguments are provided:
+
+* Passing a number as the first argument to `Buffer()` (e.g. `new Buffer(10)`)
+ allocates a new `Buffer` object of the specified size. Prior to Node.js 8.0.0,
+ the memory allocated for such `Buffer` instances is _not_ initialized and
+ _can contain sensitive data_. Such `Buffer` instances _must_ be subsequently
+ initialized by using either [`buf.fill(0)`][`buf.fill()`] or by writing to the
+ entire `Buffer` before reading data from the `Buffer`.
+ While this behavior is _intentional_ to improve performance,
+ development experience has demonstrated that a more explicit distinction is
+ required between creating a fast-but-uninitialized `Buffer` versus creating a
+ slower-but-safer `Buffer`. Since Node.js 8.0.0, `Buffer(num)` and `new
+ Buffer(num)` return a `Buffer` with initialized memory.
+* Passing a string, array, or `Buffer` as the first argument copies the
+ passed object's data into the `Buffer`.
+* Passing an [`ArrayBuffer`][] or a [`SharedArrayBuffer`][] returns a `Buffer`
+ that shares allocated memory with the given array buffer.
+
+Because the behavior of `new Buffer()` is different depending on the type of the
+first argument, security and reliability issues can be inadvertently introduced
+into applications when argument validation or `Buffer` initialization is not
+performed.
+
+For example, if an attacker can cause an application to receive a number where
+a string is expected, the application may call `new Buffer(100)`
+instead of `new Buffer("100")`, leading it to allocate a 100 byte buffer instead
+of allocating a 3 byte buffer with content `"100"`. 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.
+
+To make the creation of `Buffer` instances more reliable and less error-prone,
+the various forms of the `new Buffer()` constructor have been **deprecated**
+and replaced by separate `Buffer.from()`, [`Buffer.alloc()`][], and
+[`Buffer.allocUnsafe()`][] methods.
+
+_Developers should migrate all existing uses of the `new Buffer()` constructors
+to one of these new APIs._
+
+* [`Buffer.from(array)`][] returns a new `Buffer` that _contains a copy_ of the
+ provided octets.
+* [`Buffer.from(arrayBuffer[, byteOffset[, length]])`][`Buffer.from(arrayBuf)`]
+ returns a new `Buffer` that _shares the same allocated memory_ as the given
+ [`ArrayBuffer`][].
+* [`Buffer.from(buffer)`][] returns a new `Buffer` that _contains a copy_ of the
+ contents of the given `Buffer`.
+* [`Buffer.from(string[, encoding])`][`Buffer.from(string)`] returns a new
+ `Buffer` that _contains a copy_ of the provided string.
+* [`Buffer.alloc(size[, fill[, encoding]])`][`Buffer.alloc()`] returns a new
+ initialized `Buffer` of the specified size. This method is slower than
+ [`Buffer.allocUnsafe(size)`][`Buffer.allocUnsafe()`] but guarantees that newly
+ created `Buffer` instances never contain old data that is potentially
+ sensitive. A `TypeError` will be thrown if `size` is not a number.
+* [`Buffer.allocUnsafe(size)`][`Buffer.allocUnsafe()`] and
+ [`Buffer.allocUnsafeSlow(size)`][`Buffer.allocUnsafeSlow()`] each return a
+ new uninitialized `Buffer` of the specified `size`. Because the `Buffer` is
+ uninitialized, the allocated segment of memory might contain old data that is
+ potentially sensitive.
+
+`Buffer` instances returned by [`Buffer.allocUnsafe()`][] and
+[`Buffer.from(array)`][] _may_ be allocated off a shared internal memory pool
+if `size` is less than or equal to half [`Buffer.poolSize`][]. Instances
+returned by [`Buffer.allocUnsafeSlow()`][] _never_ use the shared internal
+memory pool.
+
+#### The `--zero-fill-buffers` command-line option
+
+
+
+Node.js can be started using the `--zero-fill-buffers` command-line option to
+cause all newly-allocated `Buffer` instances to be zero-filled upon creation by
+default. Without the option, buffers created with [`Buffer.allocUnsafe()`][],
+[`Buffer.allocUnsafeSlow()`][], and `new SlowBuffer(size)` are not zero-filled.
+Use of this flag can have a measurable negative impact on performance. Use the
+`--zero-fill-buffers` option only when necessary to enforce that newly allocated
+`Buffer` instances cannot contain old data that is potentially sensitive.
+
+```console
+$ node --zero-fill-buffers
+> Buffer.allocUnsafe(5);
+
+```
+
+#### What makes `Buffer.allocUnsafe()` and `Buffer.allocUnsafeSlow()` "unsafe"?
+
+When calling [`Buffer.allocUnsafe()`][] and [`Buffer.allocUnsafeSlow()`][], the
+segment of allocated memory is _uninitialized_ (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 `Buffer`
+created by [`Buffer.allocUnsafe()`][] without _completely_ overwriting the
+memory can allow this old data to be leaked when the `Buffer` memory is read.
+
+While there are clear performance advantages to using
+[`Buffer.allocUnsafe()`][], extra care _must_ be taken in order to avoid
+introducing security vulnerabilities into an application.
+
+[ASCII]: https://en.wikipedia.org/wiki/ASCII
+[Base64]: https://en.wikipedia.org/wiki/Base64
+[ISO-8859-1]: https://en.wikipedia.org/wiki/ISO-8859-1
+[RFC 4648, Section 5]: https://tools.ietf.org/html/rfc4648#section-5
+[UTF-16]: https://en.wikipedia.org/wiki/UTF-16
+[UTF-8]: https://en.wikipedia.org/wiki/UTF-8
+[WHATWG Encoding Standard]: https://encoding.spec.whatwg.org/
+[`ArrayBuffer`]: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/ArrayBuffer
+[`Blob`]: https://developer.mozilla.org/en-US/docs/Web/API/Blob
+[`Buffer.alloc()`]: #static-method-bufferallocsize-fill-encoding
+[`Buffer.allocUnsafe()`]: #static-method-bufferallocunsafesize
+[`Buffer.allocUnsafeSlow()`]: #static-method-bufferallocunsafeslowsize
+[`Buffer.concat()`]: #static-method-bufferconcatlist-totallength
+[`Buffer.from(array)`]: #static-method-bufferfromarray
+[`Buffer.from(arrayBuf)`]: #static-method-bufferfromarraybuffer-byteoffset-length
+[`Buffer.from(buffer)`]: #static-method-bufferfrombuffer
+[`Buffer.from(string)`]: #static-method-bufferfromstring-encoding
+[`Buffer.poolSize`]: #class-property-bufferpoolsize
+[`DataView`]: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/DataView
+[`ERR_INVALID_ARG_VALUE`]: /api/v16/errors#err_invalid_arg_value
+[`ERR_INVALID_BUFFER_SIZE`]: /api/v16/errors#err_invalid_buffer_size
+[`ERR_OUT_OF_RANGE`]: /api/v16/errors#err_out_of_range
+[`JSON.stringify()`]: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/JSON/stringify
+[`SharedArrayBuffer`]: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/SharedArrayBuffer
+[`String.prototype.indexOf()`]: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/String/indexOf
+[`String.prototype.lastIndexOf()`]: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/String/lastIndexOf
+[`String.prototype.length`]: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/String/length
+[`TypedArray.from()`]: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/TypedArray/from
+[`TypedArray.prototype.set()`]: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/TypedArray/set
+[`TypedArray.prototype.slice()`]: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/TypedArray/slice
+[`TypedArray.prototype.subarray()`]: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/TypedArray/subarray
+[`TypedArray`]: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/TypedArray
+[`Uint8Array`]: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Uint8Array
+[`buf.buffer`]: #bufbuffer
+[`buf.compare()`]: #bufcomparetarget-targetstart-targetend-sourcestart-sourceend
+[`buf.entries()`]: #bufentries
+[`buf.fill()`]: #buffillvalue-offset-end-encoding
+[`buf.indexOf()`]: #bufindexofvalue-byteoffset-encoding
+[`buf.keys()`]: #bufkeys
+[`buf.length`]: #buflength
+[`buf.slice()`]: #bufslicestart-end
+[`buf.subarray`]: #bufsubarraystart-end
+[`buf.toString()`]: #buftostringencoding-start-end
+[`buf.values()`]: #bufvalues
+[`buffer.constants.MAX_LENGTH`]: #bufferconstantsmax_length
+[`buffer.constants.MAX_STRING_LENGTH`]: #bufferconstantsmax_string_length
+[`buffer.kMaxLength`]: #bufferkmaxlength
+[`util.inspect()`]: /api/v16/util#utilinspectobject-options
+[`v8::TypedArray::kMaxLength`]: https://v8.github.io/api/head/classv8_1_1TypedArray.html#a54a48f4373da0850663c4393d843b9b0
+[base64url]: https://tools.ietf.org/html/rfc4648#section-5
+[binary strings]: https://developer.mozilla.org/en-US/docs/Web/API/DOMString/Binary
+[endianness]: https://en.wikipedia.org/wiki/Endianness
+[iterator]: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Iteration_protocols
diff --git a/content/api/v16/child_process.en.md b/content/api/v16/child_process.en.md
new file mode 100644
index 0000000000..07133468c5
--- /dev/null
+++ b/content/api/v16/child_process.en.md
@@ -0,0 +1,1637 @@
+---
+title: 'child_process'
+displayTitle: 'Child process'
+category: 'api'
+version: 'v16'
+---
+
+
+
+
+
+Stable
+
+
+
+
+
+The `node:child_process` module provides the ability to spawn subprocesses in
+a manner that is similar, but not identical, to popen(3). This capability
+is primarily provided by the [`child_process.spawn()`][] function:
+
+```js
+const { spawn } = require('node:child_process');
+const ls = spawn('ls', ['-lh', '/usr']);
+
+ls.stdout.on('data', (data) => {
+ console.log(`stdout: ${data}`);
+});
+
+ls.stderr.on('data', (data) => {
+ console.error(`stderr: ${data}`);
+});
+
+ls.on('close', (code) => {
+ console.log(`child process exited with code ${code}`);
+});
+```
+
+By default, pipes for `stdin`, `stdout`, and `stderr` 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 `{ stdio: 'ignore' }`
+option if the output will not be consumed.
+
+The command lookup is performed using the `options.env.PATH` environment
+variable if `env` is in the `options` object. Otherwise, `process.env.PATH` is
+used. If `options.env` is set without `PATH`, lookup on Unix is performed
+on a default search path search of `/usr/bin:/bin` (see your operating system's
+manual for execvpe/execvp), on Windows the current processes environment
+variable `PATH` is used.
+
+On Windows, environment variables are case-insensitive. Node.js
+lexicographically sorts the `env` 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 `env` option that have multiple variants of the same key, such as
+`PATH` and `Path`.
+
+The [`child_process.spawn()`][] method spawns the child process asynchronously,
+without blocking the Node.js event loop. The [`child_process.spawnSync()`][]
+function provides equivalent functionality in a synchronous manner that blocks
+the event loop until the spawned process either exits or is terminated.
+
+For convenience, the `node:child_process` module provides a handful of
+synchronous and asynchronous alternatives to [`child_process.spawn()`][] and
+[`child_process.spawnSync()`][]. Each of these alternatives are implemented on
+top of [`child_process.spawn()`][] or [`child_process.spawnSync()`][].
+
+* [`child_process.exec()`][]: spawns a shell and runs a command within that
+ shell, passing the `stdout` and `stderr` to a callback function when
+ complete.
+* [`child_process.execFile()`][]: similar to [`child_process.exec()`][] except
+ that it spawns the command directly without first spawning a shell by
+ default.
+* [`child_process.fork()`][]: 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.
+* [`child_process.execSync()`][]: a synchronous version of
+ [`child_process.exec()`][] that will block the Node.js event loop.
+* [`child_process.execFileSync()`][]: a synchronous version of
+ [`child_process.execFile()`][] that will block the Node.js event loop.
+
+For certain use cases, such as automating shell scripts, the
+[synchronous counterparts][] 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.
+
+### Asynchronous process creation
+
+The [`child_process.spawn()`][], [`child_process.fork()`][], [`child_process.exec()`][],
+and [`child_process.execFile()`][] methods all follow the idiomatic asynchronous
+programming pattern typical of other Node.js APIs.
+
+Each of the methods returns a [`ChildProcess`][] instance. These objects
+implement the Node.js [`EventEmitter`][] API, allowing the parent process to
+register listener functions that are called when certain events occur during
+the life cycle of the child process.
+
+The [`child_process.exec()`][] and [`child_process.execFile()`][] methods
+additionally allow for an optional `callback` function to be specified that is
+invoked when the child process terminates.
+
+#### Spawning `.bat` and `.cmd` files on Windows
+
+The importance of the distinction between [`child_process.exec()`][] and
+[`child_process.execFile()`][] can vary based on platform. On Unix-type
+operating systems (Unix, Linux, macOS) [`child_process.execFile()`][] can be
+more efficient because it does not spawn a shell by default. On Windows,
+however, `.bat` and `.cmd` files are not executable on their own without a
+terminal, and therefore cannot be launched using [`child_process.execFile()`][].
+When running on Windows, `.bat` and `.cmd` files can be invoked using
+[`child_process.spawn()`][] with the `shell` option set, with
+[`child_process.exec()`][], or by spawning `cmd.exe` and passing the `.bat` or
+`.cmd` file as an argument (which is what the `shell` option and
+[`child_process.exec()`][] do). In any case, if the script filename contains
+spaces it needs to be quoted.
+
+```js|js
+// On Windows Only...
+const { spawn } = require('node:child_process');
+const bat = spawn('cmd.exe', ['/c', 'my.bat']);
+
+bat.stdout.on('data', (data) => {
+ console.log(data.toString());
+});
+
+bat.stderr.on('data', (data) => {
+ console.error(data.toString());
+});
+
+bat.on('exit', (code) => {
+ console.log(`Child exited with code ${code}`);
+});
+--------------
+// OR...
+const { exec, spawn } = require('node:child_process');
+exec('my.bat', (err, stdout, stderr) => {
+ if (err) {
+ console.error(err);
+ return;
+ }
+ console.log(stdout);
+});
+
+// Script with spaces in the filename:
+const bat = spawn('"my script.cmd"', ['a', 'b'], { shell: true });
+// or:
+exec('"my script.cmd" a b', (err, stdout, stderr) => {
+ // ...
+});
+```
+
+#### `child_process.exec(command[, options][, callback])`
+
+
+
+* `command` [`string`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type) The command to run, with space-separated arguments.
+* `options` [`Object`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object)
+ * `cwd` [`string`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type) | [`URL`](/api/v16/url#the-whatwg-url-api) Current working directory of the child process.
+ **Default:** `process.cwd()`.
+ * `env` [`Object`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object) Environment key-value pairs. **Default:** `process.env`.
+ * `encoding` [`string`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type) **Default:** `'utf8'`
+ * `shell` [`string`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type) Shell to execute the command with. See
+ [Shell requirements][] and [Default Windows shell][]. **Default:**
+ `'/bin/sh'` on Unix, `process.env.ComSpec` on Windows.
+ * `signal` [`AbortSignal`](/api/v16/globals#abortsignal) allows aborting the child process using an
+ AbortSignal.
+ * `timeout` [`number`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type) **Default:** `0`
+ * `maxBuffer` [`number`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type) 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 [`maxBuffer` and Unicode][].
+ **Default:** `1024 * 1024`.
+ * `killSignal` [`string`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type) | [`integer`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type) **Default:** `'SIGTERM'`
+ * `uid` [`number`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type) Sets the user identity of the process (see setuid(2)).
+ * `gid` [`number`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type) Sets the group identity of the process (see setgid(2)).
+ * `windowsHide` [`boolean`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Boolean_type) Hide the subprocess console window that would
+ normally be created on Windows systems. **Default:** `false`.
+* `callback` [`Function`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Function) called with the output when process terminates.
+ * `error` [`Error`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Error)
+ * `stdout` [`string`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type) | [`Buffer`](/api/v16/buffer#buffer)
+ * `stderr` [`string`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type) | [`Buffer`](/api/v16/buffer#buffer)
+* Returns: [`ChildProcess`](/api/v16/child_process#childprocess)
+
+Spawns a shell then executes the `command` within that shell, buffering any
+generated output. The `command` string passed to the exec function is processed
+directly by the shell and special characters (vary based on
+[shell](https://en.wikipedia.org/wiki/List_of_command-line_interpreters))
+need to be dealt with accordingly:
+
+```js
+const { exec } = require('node:child_process');
+
+exec('"/path/to/test file/test.sh" arg1 arg2');
+// Double quotes are used so that the space in the path is not interpreted as
+// a delimiter of multiple arguments.
+
+exec('echo "The \\$HOME variable is $HOME"');
+// The $HOME variable is escaped in the first instance, but not in the second.
+```
+
+**Never pass unsanitized user input to this function. Any input containing shell
+metacharacters may be used to trigger arbitrary command execution.**
+
+If a `callback` function is provided, it is called with the arguments
+`(error, stdout, stderr)`. On success, `error` will be `null`. On error,
+`error` will be an instance of [`Error`][]. The `error.code` property will be
+the exit code of the process. By convention, any exit code other than `0`
+indicates an error. `error.signal` will be the signal that terminated the
+process.
+
+The `stdout` and `stderr` 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 `encoding` option
+can be used to specify the character encoding used to decode the stdout and
+stderr output. If `encoding` is `'buffer'`, or an unrecognized character
+encoding, `Buffer` objects will be passed to the callback instead.
+
+```js
+const { exec } = require('node:child_process');
+exec('cat *.js missing_file | wc -l', (error, stdout, stderr) => {
+ if (error) {
+ console.error(`exec error: ${error}`);
+ return;
+ }
+ console.log(`stdout: ${stdout}`);
+ console.error(`stderr: ${stderr}`);
+});
+```
+
+If `timeout` is greater than `0`, the parent will send the signal
+identified by the `killSignal` property (the default is `'SIGTERM'`) if the
+child runs longer than `timeout` milliseconds.
+
+Unlike the exec(3) POSIX system call, `child_process.exec()` does not replace
+the existing process and uses a shell to execute the command.
+
+If this method is invoked as its [`util.promisify()`][]ed version, it returns
+a `Promise` for an `Object` with `stdout` and `stderr` properties. The returned
+`ChildProcess` instance is attached to the `Promise` as a `child` 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 `error` object given in the
+callback, but with two additional properties `stdout` and `stderr`.
+
+```js
+const util = require('node:util');
+const exec = util.promisify(require('node:child_process').exec);
+
+async function lsExample() {
+ const { stdout, stderr } = await exec('ls');
+ console.log('stdout:', stdout);
+ console.error('stderr:', stderr);
+}
+lsExample();
+```
+
+If the `signal` option is enabled, calling `.abort()` on the corresponding
+`AbortController` is similar to calling `.kill()` on the child process except
+the error passed to the callback will be an `AbortError`:
+
+```js
+const { exec } = require('node:child_process');
+const controller = new AbortController();
+const { signal } = controller;
+const child = exec('grep ssh', { signal }, (error) => {
+ console.log(error); // an AbortError
+});
+controller.abort();
+```
+
+#### `child_process.execFile(file[, args][, options][, callback])`
+
+
+
+* `file` [`string`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type) The name or path of the executable file to run.
+* `args` string\[] List of string arguments.
+* `options` [`Object`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object)
+ * `cwd` [`string`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type) | [`URL`](/api/v16/url#the-whatwg-url-api) Current working directory of the child process.
+ * `env` [`Object`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object) Environment key-value pairs. **Default:** `process.env`.
+ * `encoding` [`string`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type) **Default:** `'utf8'`
+ * `timeout` [`number`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type) **Default:** `0`
+ * `maxBuffer` [`number`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type) 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 [`maxBuffer` and Unicode][].
+ **Default:** `1024 * 1024`.
+ * `killSignal` [`string`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type) | [`integer`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type) **Default:** `'SIGTERM'`
+ * `uid` [`number`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type) Sets the user identity of the process (see setuid(2)).
+ * `gid` [`number`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type) Sets the group identity of the process (see setgid(2)).
+ * `windowsHide` [`boolean`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Boolean_type) Hide the subprocess console window that would
+ normally be created on Windows systems. **Default:** `false`.
+ * `windowsVerbatimArguments` [`boolean`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Boolean_type) No quoting or escaping of arguments is
+ done on Windows. Ignored on Unix. **Default:** `false`.
+ * `shell` [`boolean`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Boolean_type) | [`string`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type) If `true`, runs `command` inside of a shell. Uses
+ `'/bin/sh'` on Unix, and `process.env.ComSpec` on Windows. A different
+ shell can be specified as a string. See [Shell requirements][] and
+ [Default Windows shell][]. **Default:** `false` (no shell).
+ * `signal` [`AbortSignal`](/api/v16/globals#abortsignal) allows aborting the child process using an
+ AbortSignal.
+* `callback` [`Function`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Function) Called with the output when process terminates.
+ * `error` [`Error`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Error)
+ * `stdout` [`string`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type) | [`Buffer`](/api/v16/buffer#buffer)
+ * `stderr` [`string`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type) | [`Buffer`](/api/v16/buffer#buffer)
+* Returns: [`ChildProcess`](/api/v16/child_process#childprocess)
+
+The `child_process.execFile()` function is similar to [`child_process.exec()`][]
+except that it does not spawn a shell by default. Rather, the specified
+executable `file` is spawned directly as a new process making it slightly more
+efficient than [`child_process.exec()`][].
+
+The same options as [`child_process.exec()`][] are supported. Since a shell is
+not spawned, behaviors such as I/O redirection and file globbing are not
+supported.
+
+```js
+const { execFile } = require('node:child_process');
+const child = execFile('node', ['--version'], (error, stdout, stderr) => {
+ if (error) {
+ throw error;
+ }
+ console.log(stdout);
+});
+```
+
+The `stdout` and `stderr` 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 `encoding` option
+can be used to specify the character encoding used to decode the stdout and
+stderr output. If `encoding` is `'buffer'`, or an unrecognized character
+encoding, `Buffer` objects will be passed to the callback instead.
+
+If this method is invoked as its [`util.promisify()`][]ed version, it returns
+a `Promise` for an `Object` with `stdout` and `stderr` properties. The returned
+`ChildProcess` instance is attached to the `Promise` as a `child` 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 `error` object given in the
+callback, but with two additional properties `stdout` and `stderr`.
+
+```js
+const util = require('node:util');
+const execFile = util.promisify(require('node:child_process').execFile);
+async function getVersion() {
+ const { stdout } = await execFile('node', ['--version']);
+ console.log(stdout);
+}
+getVersion();
+```
+
+**If the `shell` 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.**
+
+If the `signal` option is enabled, calling `.abort()` on the corresponding
+`AbortController` is similar to calling `.kill()` on the child process except
+the error passed to the callback will be an `AbortError`:
+
+```js
+const { execFile } = require('node:child_process');
+const controller = new AbortController();
+const { signal } = controller;
+const child = execFile('node', ['--version'], { signal }, (error) => {
+ console.log(error); // an AbortError
+});
+controller.abort();
+```
+
+#### `child_process.fork(modulePath[, args][, options])`
+
+
+
+* `modulePath` [`string`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type) | [`URL`](/api/v16/url#the-whatwg-url-api) The module to run in the child.
+* `args` string\[] List of string arguments.
+* `options` [`Object`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object)
+ * `cwd` [`string`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type) | [`URL`](/api/v16/url#the-whatwg-url-api) Current working directory of the child process.
+ * `detached` [`boolean`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Boolean_type) Prepare child to run independently of its parent
+ process. Specific behavior depends on the platform, see
+ [`options.detached`][]).
+ * `env` [`Object`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object) Environment key-value pairs. **Default:** `process.env`.
+ * `execPath` [`string`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type) Executable used to create the child process.
+ * `execArgv` string\[] List of string arguments passed to the executable.
+ **Default:** `process.execArgv`.
+ * `gid` [`number`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type) Sets the group identity of the process (see setgid(2)).
+ * `serialization` [`string`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type) Specify the kind of serialization used for sending
+ messages between processes. Possible values are `'json'` and `'advanced'`.
+ See [Advanced serialization][] for more details. **Default:** `'json'`.
+ * `signal` [`AbortSignal`](/api/v16/globals#abortsignal) Allows closing the child process using an
+ AbortSignal.
+ * `killSignal` [`string`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type) | [`integer`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type) The signal value to be used when the spawned
+ process will be killed by timeout or abort signal. **Default:** `'SIGTERM'`.
+ * `silent` [`boolean`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Boolean_type) If `true`, stdin, stdout, and stderr of the child will be
+ piped to the parent, otherwise they will be inherited from the parent, see
+ the `'pipe'` and `'inherit'` options for [`child_process.spawn()`][]'s
+ [`stdio`][] for more details. **Default:** `false`.
+ * `stdio` [`Array`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array) | [`string`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type) See [`child_process.spawn()`][]'s [`stdio`][].
+ When this option is provided, it overrides `silent`. If the array variant
+ is used, it must contain exactly one item with value `'ipc'` or an error
+ will be thrown. For instance `[0, 1, 2, 'ipc']`.
+ * `uid` [`number`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type) Sets the user identity of the process (see setuid(2)).
+ * `windowsVerbatimArguments` [`boolean`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Boolean_type) No quoting or escaping of arguments is
+ done on Windows. Ignored on Unix. **Default:** `false`.
+ * `timeout` [`number`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type) In milliseconds the maximum amount of time the process
+ is allowed to run. **Default:** `undefined`.
+* Returns: [`ChildProcess`](/api/v16/child_process#childprocess)
+
+The `child_process.fork()` method is a special case of
+[`child_process.spawn()`][] used specifically to spawn new Node.js processes.
+Like [`child_process.spawn()`][], a [`ChildProcess`][] object is returned. The
+returned [`ChildProcess`][] will have an additional communication channel
+built-in that allows messages to be passed back and forth between the parent and
+child. See [`subprocess.send()`][] for details.
+
+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.
+
+By default, `child_process.fork()` will spawn new Node.js instances using the
+[`process.execPath`][] of the parent process. The `execPath` property in the
+`options` object allows for an alternative execution path to be used.
+
+Node.js processes launched with a custom `execPath` will communicate with the
+parent process using the file descriptor (fd) identified using the
+environment variable `NODE_CHANNEL_FD` on the child process.
+
+Unlike the fork(2) POSIX system call, `child_process.fork()` does not clone the
+current process.
+
+The `shell` option available in [`child_process.spawn()`][] is not supported by
+`child_process.fork()` and will be ignored if set.
+
+If the `signal` option is enabled, calling `.abort()` on the corresponding
+`AbortController` is similar to calling `.kill()` on the child process except
+the error passed to the callback will be an `AbortError`:
+
+```js
+if (process.argv[2] === 'child') {
+ setTimeout(() => {
+ console.log(`Hello from ${process.argv[2]}!`);
+ }, 1_000);
+} else {
+ const { fork } = require('node:child_process');
+ const controller = new AbortController();
+ const { signal } = controller;
+ const child = fork(__filename, ['child'], { signal });
+ child.on('error', (err) => {
+ // This will be called with err being an AbortError if the controller aborts
+ });
+ controller.abort(); // Stops the child process
+}
+```
+
+#### `child_process.spawn(command[, args][, options])`
+
+
+
+* `command` [`string`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type) The command to run.
+* `args` string\[] List of string arguments.
+* `options` [`Object`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object)
+ * `cwd` [`string`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type) | [`URL`](/api/v16/url#the-whatwg-url-api) Current working directory of the child process.
+ * `env` [`Object`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object) Environment key-value pairs. **Default:** `process.env`.
+ * `argv0` [`string`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type) Explicitly set the value of `argv[0]` sent to the child
+ process. This will be set to `command` if not specified.
+ * `stdio` [`Array`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array) | [`string`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type) Child's stdio configuration (see
+ [`options.stdio`][`stdio`]).
+ * `detached` [`boolean`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Boolean_type) Prepare child to run independently of its parent
+ process. Specific behavior depends on the platform, see
+ [`options.detached`][]).
+ * `uid` [`number`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type) Sets the user identity of the process (see setuid(2)).
+ * `gid` [`number`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type) Sets the group identity of the process (see setgid(2)).
+ * `serialization` [`string`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type) Specify the kind of serialization used for sending
+ messages between processes. Possible values are `'json'` and `'advanced'`.
+ See [Advanced serialization][] for more details. **Default:** `'json'`.
+ * `shell` [`boolean`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Boolean_type) | [`string`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type) If `true`, runs `command` inside of a shell. Uses
+ `'/bin/sh'` on Unix, and `process.env.ComSpec` on Windows. A different
+ shell can be specified as a string. See [Shell requirements][] and
+ [Default Windows shell][]. **Default:** `false` (no shell).
+ * `windowsVerbatimArguments` [`boolean`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Boolean_type) No quoting or escaping of arguments is
+ done on Windows. Ignored on Unix. This is set to `true` automatically
+ when `shell` is specified and is CMD. **Default:** `false`.
+ * `windowsHide` [`boolean`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Boolean_type) Hide the subprocess console window that would
+ normally be created on Windows systems. **Default:** `false`.
+ * `signal` [`AbortSignal`](/api/v16/globals#abortsignal) allows aborting the child process using an
+ AbortSignal.
+ * `timeout` [`number`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type) In milliseconds the maximum amount of time the process
+ is allowed to run. **Default:** `undefined`.
+ * `killSignal` [`string`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type) | [`integer`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type) The signal value to be used when the spawned
+ process will be killed by timeout or abort signal. **Default:** `'SIGTERM'`.
+* Returns: [`ChildProcess`](/api/v16/child_process#childprocess)
+
+The `child_process.spawn()` method spawns a new process using the given
+`command`, with command-line arguments in `args`. If omitted, `args` defaults
+to an empty array.
+
+**If the `shell` 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.**
+
+A third argument may be used to specify additional options, with these defaults:
+
+```js
+const defaults = {
+ cwd: undefined,
+ env: process.env
+};
+```
+
+Use `cwd` 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 `ENOENT` error
+and exits immediately. `ENOENT` is also emitted when the command
+does not exist.
+
+Use `env` to specify environment variables that will be visible to the new
+process, the default is [`process.env`][].
+
+`undefined` values in `env` will be ignored.
+
+Example of running `ls -lh /usr`, capturing `stdout`, `stderr`, and the
+exit code:
+
+```js
+const { spawn } = require('node:child_process');
+const ls = spawn('ls', ['-lh', '/usr']);
+
+ls.stdout.on('data', (data) => {
+ console.log(`stdout: ${data}`);
+});
+
+ls.stderr.on('data', (data) => {
+ console.error(`stderr: ${data}`);
+});
+
+ls.on('close', (code) => {
+ console.log(`child process exited with code ${code}`);
+});
+```
+
+Example: A very elaborate way to run `ps ax | grep ssh`
+
+```js
+const { spawn } = require('node:child_process');
+const ps = spawn('ps', ['ax']);
+const grep = spawn('grep', ['ssh']);
+
+ps.stdout.on('data', (data) => {
+ grep.stdin.write(data);
+});
+
+ps.stderr.on('data', (data) => {
+ console.error(`ps stderr: ${data}`);
+});
+
+ps.on('close', (code) => {
+ if (code !== 0) {
+ console.log(`ps process exited with code ${code}`);
+ }
+ grep.stdin.end();
+});
+
+grep.stdout.on('data', (data) => {
+ console.log(data.toString());
+});
+
+grep.stderr.on('data', (data) => {
+ console.error(`grep stderr: ${data}`);
+});
+
+grep.on('close', (code) => {
+ if (code !== 0) {
+ console.log(`grep process exited with code ${code}`);
+ }
+});
+```
+
+Example of checking for failed `spawn`:
+
+```js
+const { spawn } = require('node:child_process');
+const subprocess = spawn('bad_command');
+
+subprocess.on('error', (err) => {
+ console.error('Failed to start subprocess.');
+});
+```
+
+Certain platforms (macOS, Linux) will use the value of `argv[0]` for the process
+title while others (Windows, SunOS) will use `command`.
+
+Node.js overwrites `argv[0]` with `process.execPath` on startup, so
+`process.argv[0]` in a Node.js child process will not match the `argv0`
+parameter passed to `spawn` from the parent. Retrieve it with the
+`process.argv0` property instead.
+
+If the `signal` option is enabled, calling `.abort()` on the corresponding
+`AbortController` is similar to calling `.kill()` on the child process except
+the error passed to the callback will be an `AbortError`:
+
+```js
+const { spawn } = require('node:child_process');
+const controller = new AbortController();
+const { signal } = controller;
+const grep = spawn('grep', ['ssh'], { signal });
+grep.on('error', (err) => {
+ // This will be called with err being an AbortError if the controller aborts
+});
+controller.abort(); // Stops the child process
+```
+
+##### `options.detached`
+
+
+
+On Windows, setting `options.detached` to `true` 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.
+
+On non-Windows platforms, if `options.detached` is set to `true`, 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 setsid(2) for more information.
+
+By default, the parent will wait for the detached child to exit. To prevent the
+parent from waiting for a given `subprocess` to exit, use the
+`subprocess.unref()` 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.
+
+When using the `detached` 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 `stdio` configuration that is not connected to the parent.
+If the parent's `stdio` is inherited, the child will remain attached to the
+controlling terminal.
+
+Example of a long-running process, by detaching and also ignoring its parent
+`stdio` file descriptors, in order to ignore the parent's termination:
+
+```js
+const { spawn } = require('node:child_process');
+
+const subprocess = spawn(process.argv[0], ['child_program.js'], {
+ detached: true,
+ stdio: 'ignore'
+});
+
+subprocess.unref();
+```
+
+Alternatively one can redirect the child process' output into files:
+
+```js
+const fs = require('node:fs');
+const { spawn } = require('node:child_process');
+const out = fs.openSync('./out.log', 'a');
+const err = fs.openSync('./out.log', 'a');
+
+const subprocess = spawn('prg', [], {
+ detached: true,
+ stdio: [ 'ignore', out, err ]
+});
+
+subprocess.unref();
+```
+
+##### `options.stdio`
+
+
+
+The `options.stdio` 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 [`subprocess.stdin`][],
+[`subprocess.stdout`][], and [`subprocess.stderr`][] streams on the
+[`ChildProcess`][] object. This is equivalent to setting the `options.stdio`
+equal to `['pipe', 'pipe', 'pipe']`.
+
+For convenience, `options.stdio` may be one of the following strings:
+
+* `'pipe'`: equivalent to `['pipe', 'pipe', 'pipe']` (the default)
+* `'overlapped'`: equivalent to `['overlapped', 'overlapped', 'overlapped']`
+* `'ignore'`: equivalent to `['ignore', 'ignore', 'ignore']`
+* `'inherit'`: equivalent to `['inherit', 'inherit', 'inherit']` or `[0, 1, 2]`
+
+Otherwise, the value of `options.stdio` 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:
+
+1. `'pipe'`: 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
+ `child_process` object as [`subprocess.stdio[fd]`][`subprocess.stdio`]. Pipes
+ created for fds 0, 1, and 2 are also available as [`subprocess.stdin`][],
+ [`subprocess.stdout`][] and [`subprocess.stderr`][], respectively.
+ These are not actual Unix pipes and therefore the child process
+ can not use them by their descriptor files,
+ e.g. `/dev/fd/2` or `/dev/stdout`.
+2. `'overlapped'`: Same as `'pipe'` except that the `FILE_FLAG_OVERLAPPED` flag
+ is set on the handle. This is necessary for overlapped I/O on the child
+ process's stdio handles. See the
+ [docs](https://docs.microsoft.com/en-us/windows/win32/fileio/synchronous-and-asynchronous-i-o)
+ for more details. This is exactly the same as `'pipe'` on non-Windows
+ systems.
+3. `'ipc'`: Create an IPC channel for passing messages/file descriptors
+ between parent and child. A [`ChildProcess`][] may have at most one IPC
+ stdio file descriptor. Setting this option enables the
+ [`subprocess.send()`][] method. If the child is a Node.js process, the
+ presence of an IPC channel will enable [`process.send()`][] and
+ [`process.disconnect()`][] methods, as well as [`'disconnect'`][] and
+ [`'message'`][] events within the child.
+
+ Accessing the IPC channel fd in any way other than [`process.send()`][]
+ or using the IPC channel with a child process that is not a Node.js instance
+ is not supported.
+4. `'ignore'`: 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 `'ignore'` will cause Node.js to open `/dev/null` and attach it to the
+ child's fd.
+5. `'inherit'`: Pass through the corresponding stdio stream to/from the
+ parent process. In the first three positions, this is equivalent to
+ `process.stdin`, `process.stdout`, and `process.stderr`, respectively. In
+ any other position, equivalent to `'ignore'`.
+6. [`Stream`](/api/v16/stream#stream) 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 `stdio` array. The stream must have an
+ underlying descriptor (file streams do not until the `'open'` event has
+ occurred).
+7. 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 [`Stream`](/api/v16/stream#stream) objects can be shared. Passing sockets
+ is not supported on Windows.
+8. `null`, `undefined`: 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 `'ignore'`.
+
+```js
+const { spawn } = require('node:child_process');
+
+// Child will use parent's stdios.
+spawn('prg', [], { stdio: 'inherit' });
+
+// Spawn child sharing only stderr.
+spawn('prg', [], { stdio: ['pipe', 'pipe', process.stderr] });
+
+// Open an extra fd=4, to interact with programs presenting a
+// startd-style interface.
+spawn('prg', [], { stdio: ['pipe', null, null, null, 'pipe'] });
+```
+
+_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 `unref()`) until the
+child registers an event handler for the [`'disconnect'`][] event
+or the [`'message'`][] event. This allows the child to exit
+normally without the process being held open by the open IPC channel._
+
+On Unix-like operating systems, the [`child_process.spawn()`][] method
+performs memory operations synchronously before decoupling the event loop
+from the child. Applications with a large memory footprint may find frequent
+[`child_process.spawn()`][] calls to be a bottleneck. For more information,
+see [V8 issue 7381](https://bugs.chromium.org/p/v8/issues/detail?id=7381).
+
+See also: [`child_process.exec()`][] and [`child_process.fork()`][].
+
+### Synchronous process creation
+
+The [`child_process.spawnSync()`][], [`child_process.execSync()`][], and
+[`child_process.execFileSync()`][] methods are synchronous and will block the
+Node.js event loop, pausing execution of any additional code until the spawned
+process exits.
+
+Blocking calls like these are mostly useful for simplifying general-purpose
+scripting tasks and for simplifying the loading/processing of application
+configuration at startup.
+
+#### `child_process.execFileSync(file[, args][, options])`
+
+
+
+* `file` [`string`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type) The name or path of the executable file to run.
+* `args` string\[] List of string arguments.
+* `options` [`Object`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object)
+ * `cwd` [`string`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type) | [`URL`](/api/v16/url#the-whatwg-url-api) Current working directory of the child process.
+ * `input` [`string`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type) | [`Buffer`](/api/v16/buffer#buffer) | [`TypedArray`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/TypedArray) | [`DataView`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/DataView) The value which will be passed
+ as stdin to the spawned process. Supplying this value will override
+ `stdio[0]`.
+ * `stdio` [`string`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type) | [`Array`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array) Child's stdio configuration. `stderr` by default will
+ be output to the parent process' stderr unless `stdio` is specified.
+ **Default:** `'pipe'`.
+ * `env` [`Object`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object) Environment key-value pairs. **Default:** `process.env`.
+ * `uid` [`number`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type) Sets the user identity of the process (see setuid(2)).
+ * `gid` [`number`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type) Sets the group identity of the process (see setgid(2)).
+ * `timeout` [`number`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type) In milliseconds the maximum amount of time the process
+ is allowed to run. **Default:** `undefined`.
+ * `killSignal` [`string`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type) | [`integer`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type) The signal value to be used when the spawned
+ process will be killed. **Default:** `'SIGTERM'`.
+ * `maxBuffer` [`number`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type) Largest amount of data in bytes allowed on stdout or
+ stderr. If exceeded, the child process is terminated. See caveat at
+ [`maxBuffer` and Unicode][]. **Default:** `1024 * 1024`.
+ * `encoding` [`string`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type) The encoding used for all stdio inputs and outputs.
+ **Default:** `'buffer'`.
+ * `windowsHide` [`boolean`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Boolean_type) Hide the subprocess console window that would
+ normally be created on Windows systems. **Default:** `false`.
+ * `shell` [`boolean`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Boolean_type) | [`string`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type) If `true`, runs `command` inside of a shell. Uses
+ `'/bin/sh'` on Unix, and `process.env.ComSpec` on Windows. A different
+ shell can be specified as a string. See [Shell requirements][] and
+ [Default Windows shell][]. **Default:** `false` (no shell).
+* Returns: [`Buffer`](/api/v16/buffer#buffer) | [`string`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type) The stdout from the command.
+
+The `child_process.execFileSync()` method is generally identical to
+[`child_process.execFile()`][] with the exception that the method will not
+return until the child process has fully closed. When a timeout has been
+encountered and `killSignal` is sent, the method won't return until the process
+has completely exited.
+
+If the child process intercepts and handles the `SIGTERM` signal and
+does not exit, the parent process will still wait until the child process has
+exited.
+
+If the process times out or has a non-zero exit code, this method will throw an
+[`Error`][] that will include the full result of the underlying
+[`child_process.spawnSync()`][].
+
+**If the `shell` 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.**
+
+#### `child_process.execSync(command[, options])`
+
+
+
+* `command` [`string`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type) The command to run.
+* `options` [`Object`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object)
+ * `cwd` [`string`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type) | [`URL`](/api/v16/url#the-whatwg-url-api) Current working directory of the child process.
+ * `input` [`string`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type) | [`Buffer`](/api/v16/buffer#buffer) | [`TypedArray`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/TypedArray) | [`DataView`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/DataView) The value which will be passed
+ as stdin to the spawned process. Supplying this value will override
+ `stdio[0]`.
+ * `stdio` [`string`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type) | [`Array`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array) Child's stdio configuration. `stderr` by default will
+ be output to the parent process' stderr unless `stdio` is specified.
+ **Default:** `'pipe'`.
+ * `env` [`Object`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object) Environment key-value pairs. **Default:** `process.env`.
+ * `shell` [`string`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type) Shell to execute the command with. See
+ [Shell requirements][] and [Default Windows shell][]. **Default:**
+ `'/bin/sh'` on Unix, `process.env.ComSpec` on Windows.
+ * `uid` [`number`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type) Sets the user identity of the process. (See setuid(2)).
+ * `gid` [`number`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type) Sets the group identity of the process. (See setgid(2)).
+ * `timeout` [`number`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type) In milliseconds the maximum amount of time the process
+ is allowed to run. **Default:** `undefined`.
+ * `killSignal` [`string`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type) | [`integer`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type) The signal value to be used when the spawned
+ process will be killed. **Default:** `'SIGTERM'`.
+ * `maxBuffer` [`number`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type) 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 [`maxBuffer` and Unicode][].
+ **Default:** `1024 * 1024`.
+ * `encoding` [`string`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type) The encoding used for all stdio inputs and outputs.
+ **Default:** `'buffer'`.
+ * `windowsHide` [`boolean`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Boolean_type) Hide the subprocess console window that would
+ normally be created on Windows systems. **Default:** `false`.
+* Returns: [`Buffer`](/api/v16/buffer#buffer) | [`string`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type) The stdout from the command.
+
+The `child_process.execSync()` method is generally identical to
+[`child_process.exec()`][] with the exception that the method will not return
+until the child process has fully closed. When a timeout has been encountered
+and `killSignal` is sent, the method won't return until the process has
+completely exited. If the child process intercepts and handles the `SIGTERM`
+signal and doesn't exit, the parent process will wait until the child process
+has exited.
+
+If the process times out or has a non-zero exit code, this method will throw.
+The [`Error`][] object will contain the entire result from
+[`child_process.spawnSync()`][].
+
+**Never pass unsanitized user input to this function. Any input containing shell
+metacharacters may be used to trigger arbitrary command execution.**
+
+#### `child_process.spawnSync(command[, args][, options])`
+
+
+
+* `command` [`string`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type) The command to run.
+* `args` string\[] List of string arguments.
+* `options` [`Object`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object)
+ * `cwd` [`string`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type) | [`URL`](/api/v16/url#the-whatwg-url-api) Current working directory of the child process.
+ * `input` [`string`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type) | [`Buffer`](/api/v16/buffer#buffer) | [`TypedArray`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/TypedArray) | [`DataView`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/DataView) The value which will be passed
+ as stdin to the spawned process. Supplying this value will override
+ `stdio[0]`.
+ * `argv0` [`string`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type) Explicitly set the value of `argv[0]` sent to the child
+ process. This will be set to `command` if not specified.
+ * `stdio` [`string`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type) | [`Array`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array) Child's stdio configuration.
+ * `env` [`Object`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object) Environment key-value pairs. **Default:** `process.env`.
+ * `uid` [`number`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type) Sets the user identity of the process (see setuid(2)).
+ * `gid` [`number`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type) Sets the group identity of the process (see setgid(2)).
+ * `timeout` [`number`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type) In milliseconds the maximum amount of time the process
+ is allowed to run. **Default:** `undefined`.
+ * `killSignal` [`string`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type) | [`integer`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type) The signal value to be used when the spawned
+ process will be killed. **Default:** `'SIGTERM'`.
+ * `maxBuffer` [`number`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type) 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 [`maxBuffer` and Unicode][].
+ **Default:** `1024 * 1024`.
+ * `encoding` [`string`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type) The encoding used for all stdio inputs and outputs.
+ **Default:** `'buffer'`.
+ * `shell` [`boolean`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Boolean_type) | [`string`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type) If `true`, runs `command` inside of a shell. Uses
+ `'/bin/sh'` on Unix, and `process.env.ComSpec` on Windows. A different
+ shell can be specified as a string. See [Shell requirements][] and
+ [Default Windows shell][]. **Default:** `false` (no shell).
+ * `windowsVerbatimArguments` [`boolean`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Boolean_type) No quoting or escaping of arguments is
+ done on Windows. Ignored on Unix. This is set to `true` automatically
+ when `shell` is specified and is CMD. **Default:** `false`.
+ * `windowsHide` [`boolean`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Boolean_type) Hide the subprocess console window that would
+ normally be created on Windows systems. **Default:** `false`.
+* Returns: [`Object`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object)
+ * `pid` [`number`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type) Pid of the child process.
+ * `output` [`Array`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array) Array of results from stdio output.
+ * `stdout` [`Buffer`](/api/v16/buffer#buffer) | [`string`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type) The contents of `output[1]`.
+ * `stderr` [`Buffer`](/api/v16/buffer#buffer) | [`string`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type) The contents of `output[2]`.
+ * `status` [`number`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type) | [`null`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Null_type) The exit code of the subprocess, or `null` if the
+ subprocess terminated due to a signal.
+ * `signal` [`string`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type) | [`null`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Null_type) The signal used to kill the subprocess, or `null` if
+ the subprocess did not terminate due to a signal.
+ * `error` [`Error`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Error) The error object if the child process failed or timed out.
+
+The `child_process.spawnSync()` method is generally identical to
+[`child_process.spawn()`][] with the exception that the function will not return
+until the child process has fully closed. When a timeout has been encountered
+and `killSignal` is sent, the method won't return until the process has
+completely exited. If the process intercepts and handles the `SIGTERM` signal
+and doesn't exit, the parent process will wait until the child process has
+exited.
+
+**If the `shell` 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.**
+
+### `ChildProcess`
+
+
+
+* Extends: [`EventEmitter`](/api/v16/events#eventemitter)
+
+Instances of the `ChildProcess` represent spawned child processes.
+
+Instances of `ChildProcess` are not intended to be created directly. Rather,
+use the [`child_process.spawn()`][], [`child_process.exec()`][],
+[`child_process.execFile()`][], or [`child_process.fork()`][] methods to create
+instances of `ChildProcess`.
+
+#### `'close'`
+
+
+
+* `code` [`number`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type) The exit code if the child exited on its own.
+* `signal` [`string`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type) The signal by which the child process was terminated.
+
+The `'close'` event is emitted after a process has ended _and_ the stdio
+streams of a child process have been closed. This is distinct from the
+[`'exit'`][] event, since multiple processes might share the same stdio
+streams. The `'close'` event will always emit after [`'exit'`][] was
+already emitted, or [`'error'`][] if the child failed to spawn.
+
+```js
+const { spawn } = require('node:child_process');
+const ls = spawn('ls', ['-lh', '/usr']);
+
+ls.stdout.on('data', (data) => {
+ console.log(`stdout: ${data}`);
+});
+
+ls.on('close', (code) => {
+ console.log(`child process close all stdio with code ${code}`);
+});
+
+ls.on('exit', (code) => {
+ console.log(`child process exited with code ${code}`);
+});
+```
+
+#### `'disconnect'`
+
+
+
+The `'disconnect'` event is emitted after calling the
+[`subprocess.disconnect()`][] method in parent process or
+[`process.disconnect()`][] in child process. After disconnecting it is no longer
+possible to send or receive messages, and the [`subprocess.connected`][]
+property is `false`.
+
+#### `'error'`
+
+* `err` [`Error`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Error) The error.
+
+The `'error'` event is emitted whenever:
+
+1. The process could not be spawned, or
+2. The process could not be killed, or
+3. Sending a message to the child process failed.
+
+The `'exit'` event may or may not fire after an error has occurred. When
+listening to both the `'exit'` and `'error'` events, guard
+against accidentally invoking handler functions multiple times.
+
+See also [`subprocess.kill()`][] and [`subprocess.send()`][].
+
+#### `'exit'`
+
+
+
+* `code` [`number`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type) The exit code if the child exited on its own.
+* `signal` [`string`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type) The signal by which the child process was terminated.
+
+The `'exit'` event is emitted after the child process ends. If the process
+exited, `code` is the final exit code of the process, otherwise `null`. If the
+process terminated due to receipt of a signal, `signal` is the string name of
+the signal, otherwise `null`. One of the two will always be non-`null`.
+
+When the `'exit'` event is triggered, child process stdio streams might still be
+open.
+
+Node.js establishes signal handlers for `SIGINT` and `SIGTERM` 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.
+
+See waitpid(2).
+
+#### `'message'`
+
+
+
+* `message` [`Object`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object) A parsed JSON object or primitive value.
+* `sendHandle` [`Handle`](/api/v16/net#serverlistenhandle-backlog-callback) A [`net.Socket`][] or [`net.Server`][] object, or
+ undefined.
+
+The `'message'` event is triggered when a child process uses
+[`process.send()`][] to send messages.
+
+The message goes through serialization and parsing. The resulting
+message might not be the same as what is originally sent.
+
+If the `serialization` option was set to `'advanced'` used when spawning the
+child process, the `message` argument can contain data that JSON is not able
+to represent.
+See [Advanced serialization][] for more details.
+
+#### `'spawn'`
+
+
+
+The `'spawn'` event is emitted once the child process has spawned successfully.
+If the child process does not spawn successfully, the `'spawn'` event is not
+emitted and the `'error'` event is emitted instead.
+
+If emitted, the `'spawn'` event comes before all other events and before any
+data is received via `stdout` or `stderr`.
+
+The `'spawn'` event will fire regardless of whether an error occurs **within**
+the spawned process. For example, if `bash some-command` spawns successfully,
+the `'spawn'` event will fire, though `bash` may fail to spawn `some-command`.
+This caveat also applies when using `{ shell: true }`.
+
+#### `subprocess.channel`
+
+
+
+* [`Object`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object) A pipe representing the IPC channel to the child process.
+
+The `subprocess.channel` property is a reference to the child's IPC channel. If
+no IPC channel exists, this property is `undefined`.
+
+##### `subprocess.channel.ref()`
+
+
+
+This method makes the IPC channel keep the event loop of the parent process
+running if `.unref()` has been called before.
+
+##### `subprocess.channel.unref()`
+
+
+
+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.
+
+#### `subprocess.connected`
+
+
+
+* [`boolean`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Boolean_type) Set to `false` after `subprocess.disconnect()` is called.
+
+The `subprocess.connected` property indicates whether it is still possible to
+send and receive messages from a child process. When `subprocess.connected` is
+`false`, it is no longer possible to send or receive messages.
+
+#### `subprocess.disconnect()`
+
+
+
+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 `subprocess.connected` and `process.connected` properties in
+both the parent and child (respectively) will be set to `false`, and it will be
+no longer possible to pass messages between the processes.
+
+The `'disconnect'` event will be emitted when there are no messages in the
+process of being received. This will most often be triggered immediately after
+calling `subprocess.disconnect()`.
+
+When the child process is a Node.js instance (e.g. spawned using
+[`child_process.fork()`][]), the `process.disconnect()` method can be invoked
+within the child process to close the IPC channel as well.
+
+#### `subprocess.exitCode`
+
+* [`integer`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type)
+
+The `subprocess.exitCode` property indicates the exit code of the child process.
+If the child process is still running, the field will be `null`.
+
+#### `subprocess.kill([signal])`
+
+
+
+* `signal` [`number`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type) | [`string`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type)
+* Returns: [`boolean`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Boolean_type)
+
+The `subprocess.kill()` method sends a signal to the child process. If no
+argument is given, the process will be sent the `'SIGTERM'` signal. See
+signal(7) for a list of available signals. This function returns `true` if
+kill(2) succeeds, and `false` otherwise.
+
+```js
+const { spawn } = require('node:child_process');
+const grep = spawn('grep', ['ssh']);
+
+grep.on('close', (code, signal) => {
+ console.log(
+ `child process terminated due to receipt of signal ${signal}`);
+});
+
+// Send SIGHUP to process.
+grep.kill('SIGHUP');
+```
+
+The [`ChildProcess`][] object may emit an [`'error'`][] 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.
+
+While the function is called `kill`, the signal delivered to the child process
+may not actually terminate the process.
+
+See kill(2) for reference.
+
+On Windows, where POSIX signals do not exist, the `signal` argument will be
+ignored, and the process will be killed forcefully and abruptly (similar to
+`'SIGKILL'`).
+See [Signal Events][] for more details.
+
+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 `shell` option of `ChildProcess`:
+
+```js
+'use strict';
+const { spawn } = require('node:child_process');
+
+const subprocess = spawn(
+ 'sh',
+ [
+ '-c',
+ `node -e "setInterval(() => {
+ console.log(process.pid, 'is alive')
+ }, 500);"`,
+ ], {
+ stdio: ['inherit', 'inherit', 'inherit']
+ }
+);
+
+setTimeout(() => {
+ subprocess.kill(); // Does not terminate the Node.js process in the shell.
+}, 2000);
+```
+
+#### `subprocess.killed`
+
+
+
+* [`boolean`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Boolean_type) Set to `true` after `subprocess.kill()` is used to successfully
+ send a signal to the child process.
+
+The `subprocess.killed` property indicates whether the child process
+successfully received a signal from `subprocess.kill()`. The `killed` property
+does not indicate that the child process has been terminated.
+
+#### `subprocess.pid`
+
+
+
+* [`integer`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type) | [`undefined`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Undefined_type)
+
+Returns the process identifier (PID) of the child process. If the child process
+fails to spawn due to errors, then the value is `undefined` and `error` is
+emitted.
+
+```js
+const { spawn } = require('node:child_process');
+const grep = spawn('grep', ['ssh']);
+
+console.log(`Spawned child pid: ${grep.pid}`);
+grep.stdin.end();
+```
+
+#### `subprocess.ref()`
+
+
+
+Calling `subprocess.ref()` after making a call to `subprocess.unref()` will
+restore the removed reference count for the child process, forcing the parent
+to wait for the child to exit before exiting itself.
+
+```js
+const { spawn } = require('node:child_process');
+
+const subprocess = spawn(process.argv[0], ['child_program.js'], {
+ detached: true,
+ stdio: 'ignore'
+});
+
+subprocess.unref();
+subprocess.ref();
+```
+
+#### `subprocess.send(message[, sendHandle[, options]][, callback])`
+
+
+
+* `message` [`Object`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object)
+* `sendHandle` [`Handle`](/api/v16/net#serverlistenhandle-backlog-callback)
+* `options` [`Object`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object) The `options` argument, if present, is an object used to
+ parameterize the sending of certain types of handles. `options` supports
+ the following properties:
+ * `keepOpen` [`boolean`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Boolean_type) A value that can be used when passing instances of
+ `net.Socket`. When `true`, the socket is kept open in the sending process.
+ **Default:** `false`.
+* `callback` [`Function`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Function)
+* Returns: [`boolean`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Boolean_type)
+
+When an IPC channel has been established between the parent and child (
+i.e. when using [`child_process.fork()`][]), the `subprocess.send()` 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 [`'message'`][] event.
+
+The message goes through serialization and parsing. The resulting
+message might not be the same as what is originally sent.
+
+For example, in the parent script:
+
+```js
+const cp = require('node:child_process');
+const n = cp.fork(`${__dirname}/sub.js`);
+
+n.on('message', (m) => {
+ console.log('PARENT got message:', m);
+});
+
+// Causes the child to print: CHILD got message: { hello: 'world' }
+n.send({ hello: 'world' });
+```
+
+And then the child script, `'sub.js'` might look like this:
+
+```js
+process.on('message', (m) => {
+ console.log('CHILD got message:', m);
+});
+
+// Causes the parent to print: PARENT got message: { foo: 'bar', baz: null }
+process.send({ foo: 'bar', baz: NaN });
+```
+
+Child Node.js processes will have a [`process.send()`][] method of their own
+that allows the child to send messages back to the parent.
+
+There is a special case when sending a `{cmd: 'NODE_foo'}` message. Messages
+containing a `NODE_` prefix in the `cmd` property are reserved for use within
+Node.js core and will not be emitted in the child's [`'message'`][]
+event. Rather, such messages are emitted using the
+`'internalMessage'` event and are consumed internally by Node.js.
+Applications should avoid using such messages or listening for
+`'internalMessage'` events as it is subject to change without notice.
+
+The optional `sendHandle` argument that may be passed to `subprocess.send()` 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 [`'message'`][] event. Any data that is received
+and buffered in the socket will not be sent to the child.
+
+The optional `callback` 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: `null` on success, or an [`Error`][] object on failure.
+
+If no `callback` function is provided and the message cannot be sent, an
+`'error'` event will be emitted by the [`ChildProcess`][] object. This can
+happen, for instance, when the child process has already exited.
+
+`subprocess.send()` will return `false` 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 `true`. The `callback` function can be
+used to implement flow control.
+
+##### Example: sending a server object
+
+The `sendHandle` 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:
+
+```js
+const subprocess = require('node:child_process').fork('subprocess.js');
+
+// Open up the server object and send the handle.
+const server = require('node:net').createServer();
+server.on('connection', (socket) => {
+ socket.end('handled by parent');
+});
+server.listen(1337, () => {
+ subprocess.send('server', server);
+});
+```
+
+The child would then receive the server object as:
+
+```js
+process.on('message', (m, server) => {
+ if (m === 'server') {
+ server.on('connection', (socket) => {
+ socket.end('handled by child');
+ });
+ }
+});
+```
+
+Once the server is now shared between the parent and child, some connections
+can be handled by the parent and some by the child.
+
+While the example above uses a server created using the `node:net` module,
+`node:dgram` module servers use exactly the same workflow with the exceptions of
+listening on a `'message'` event instead of `'connection'` and using
+`server.bind()` instead of `server.listen()`. This is, however, only
+supported on Unix platforms.
+
+##### Example: sending a socket object
+
+Similarly, the `sendHandler` 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:
+
+```js
+const { fork } = require('node:child_process');
+const normal = fork('subprocess.js', ['normal']);
+const special = fork('subprocess.js', ['special']);
+
+// Open up the server and send sockets to child. Use pauseOnConnect to prevent
+// the sockets from being read before they are sent to the child process.
+const server = require('node:net').createServer({ pauseOnConnect: true });
+server.on('connection', (socket) => {
+
+ // If this is special priority...
+ if (socket.remoteAddress === '74.125.127.100') {
+ special.send('socket', socket);
+ return;
+ }
+ // This is normal priority.
+ normal.send('socket', socket);
+});
+server.listen(1337);
+```
+
+The `subprocess.js` would receive the socket handle as the second argument
+passed to the event callback function:
+
+```js
+process.on('message', (m, socket) => {
+ if (m === 'socket') {
+ if (socket) {
+ // Check that the client socket exists.
+ // It is possible for the socket to be closed between the time it is
+ // sent and the time it is received in the child process.
+ socket.end(`Request handled with ${process.argv[2]} priority`);
+ }
+ }
+});
+```
+
+Do not use `.maxConnections` on a socket that has been passed to a subprocess.
+The parent cannot track when the socket is destroyed.
+
+Any `'message'` handlers in the subprocess should verify that `socket` exists,
+as the connection may have been closed during the time it takes to send the
+connection to the child.
+
+#### `subprocess.signalCode`
+
+* [`string`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type) | [`null`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Null_type)
+
+The `subprocess.signalCode` property indicates the signal received by
+the child process if any, else `null`.
+
+#### `subprocess.spawnargs`
+
+* [`Array`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array)
+
+The `subprocess.spawnargs` property represents the full list of command-line
+arguments the child process was launched with.
+
+#### `subprocess.spawnfile`
+
+* [`string`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type)
+
+The `subprocess.spawnfile` property indicates the executable file name of
+the child process that is launched.
+
+For [`child_process.fork()`][], its value will be equal to
+[`process.execPath`][].
+For [`child_process.spawn()`][], its value will be the name of
+the executable file.
+For [`child_process.exec()`][], its value will be the name of the shell
+in which the child process is launched.
+
+#### `subprocess.stderr`
+
+
+
+* [`stream.Readable`](/api/v16/stream#streamreadable) | [`null`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Null_type) | [`undefined`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Undefined_type)
+
+A `Readable Stream` that represents the child process's `stderr`.
+
+If the child was spawned with `stdio[2]` set to anything other than `'pipe'`,
+then this will be `null`.
+
+`subprocess.stderr` is an alias for `subprocess.stdio[2]`. Both properties will
+refer to the same value.
+
+The `subprocess.stderr` property can be `null` or `undefined`
+if the child process could not be successfully spawned.
+
+#### `subprocess.stdin`
+
+
+
+* [`stream.Writable`](/api/v16/stream#streamwritable) | [`null`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Null_type) | [`undefined`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Undefined_type)
+
+A `Writable Stream` that represents the child process's `stdin`.
+
+If a child process waits to read all of its input, the child will not continue
+until this stream has been closed via `end()`.
+
+If the child was spawned with `stdio[0]` set to anything other than `'pipe'`,
+then this will be `null`.
+
+`subprocess.stdin` is an alias for `subprocess.stdio[0]`. Both properties will
+refer to the same value.
+
+The `subprocess.stdin` property can be `null` or `undefined`
+if the child process could not be successfully spawned.
+
+#### `subprocess.stdio`
+
+
+
+* [`Array`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array)
+
+A sparse array of pipes to the child process, corresponding with positions in
+the [`stdio`][] option passed to [`child_process.spawn()`][] that have been set
+to the value `'pipe'`. `subprocess.stdio[0]`, `subprocess.stdio[1]`, and
+`subprocess.stdio[2]` are also available as `subprocess.stdin`,
+`subprocess.stdout`, and `subprocess.stderr`, respectively.
+
+In the following example, only the child's fd `1` (stdout) is configured as a
+pipe, so only the parent's `subprocess.stdio[1]` is a stream, all other values
+in the array are `null`.
+
+```js
+const assert = require('node:assert');
+const fs = require('node:fs');
+const child_process = require('node:child_process');
+
+const subprocess = child_process.spawn('ls', {
+ stdio: [
+ 0, // Use parent's stdin for child.
+ 'pipe', // Pipe child's stdout to parent.
+ fs.openSync('err.out', 'w'), // Direct child's stderr to a file.
+ ]
+});
+
+assert.strictEqual(subprocess.stdio[0], null);
+assert.strictEqual(subprocess.stdio[0], subprocess.stdin);
+
+assert(subprocess.stdout);
+assert.strictEqual(subprocess.stdio[1], subprocess.stdout);
+
+assert.strictEqual(subprocess.stdio[2], null);
+assert.strictEqual(subprocess.stdio[2], subprocess.stderr);
+```
+
+The `subprocess.stdio` property can be `undefined` if the child process could
+not be successfully spawned.
+
+#### `subprocess.stdout`
+
+
+
+* [`stream.Readable`](/api/v16/stream#streamreadable) | [`null`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Null_type) | [`undefined`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Undefined_type)
+
+A `Readable Stream` that represents the child process's `stdout`.
+
+If the child was spawned with `stdio[1]` set to anything other than `'pipe'`,
+then this will be `null`.
+
+`subprocess.stdout` is an alias for `subprocess.stdio[1]`. Both properties will
+refer to the same value.
+
+```js
+const { spawn } = require('node:child_process');
+
+const subprocess = spawn('ls');
+
+subprocess.stdout.on('data', (data) => {
+ console.log(`Received chunk ${data}`);
+});
+```
+
+The `subprocess.stdout` property can be `null` or `undefined`
+if the child process could not be successfully spawned.
+
+#### `subprocess.unref()`
+
+
+
+By default, the parent will wait for the detached child to exit. To prevent the
+parent from waiting for a given `subprocess` to exit, use the
+`subprocess.unref()` 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.
+
+```js
+const { spawn } = require('node:child_process');
+
+const subprocess = spawn(process.argv[0], ['child_program.js'], {
+ detached: true,
+ stdio: 'ignore'
+});
+
+subprocess.unref();
+```
+
+### `maxBuffer` and Unicode
+
+The `maxBuffer` option specifies the largest number of bytes allowed on `stdout`
+or `stderr`. 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, `console.log('中文测试')` will send 13 UTF-8 encoded bytes
+to `stdout` although there are only 4 characters.
+
+### Shell requirements
+
+The shell should understand the `-c` switch. If the shell is `'cmd.exe'`, it
+should understand the `/d /s /c` switches and command-line parsing should be
+compatible.
+
+### Default Windows shell
+
+Although Microsoft specifies `%COMSPEC%` must contain the path to
+`'cmd.exe'` in the root environment, child processes are not always subject to
+the same requirement. Thus, in `child_process` functions where a shell can be
+spawned, `'cmd.exe'` is used as a fallback if `process.env.ComSpec` is
+unavailable.
+
+### Advanced serialization
+
+
+
+Child processes support a serialization mechanism for IPC that is based on the
+[serialization API of the `node:v8` module][v8.serdes], based on the
+[HTML structured clone algorithm][]. This is generally more powerful and
+supports more built-in JavaScript object types, such as `BigInt`, `Map`
+and `Set`, `ArrayBuffer` and `TypedArray`, `Buffer`, `Error`, `RegExp` etc.
+
+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
+`serialization` option to `'advanced'` when calling [`child_process.spawn()`][]
+or [`child_process.fork()`][].
+
+[Advanced serialization]: #advanced-serialization
+[Default Windows shell]: #default-windows-shell
+[HTML structured clone algorithm]: https://developer.mozilla.org/en-US/docs/Web/API/Web_Workers_API/Structured_clone_algorithm
+[Shell requirements]: #shell-requirements
+[Signal Events]: /api/v16/process#signal-events
+[`'disconnect'`]: /api/v16/process#event-disconnect
+[`'error'`]: #event-error
+[`'exit'`]: #event-exit
+[`'message'`]: /api/v16/process#event-message
+[`ChildProcess`]: #class-childprocess
+[`Error`]: /api/v16/errors#class-error
+[`EventEmitter`]: /api/v16/events#class-eventemitter
+[`child_process.exec()`]: #child_processexeccommand-options-callback
+[`child_process.execFile()`]: #child_processexecfilefile-args-options-callback
+[`child_process.execFileSync()`]: #child_processexecfilesyncfile-args-options
+[`child_process.execSync()`]: #child_processexecsynccommand-options
+[`child_process.fork()`]: #child_processforkmodulepath-args-options
+[`child_process.spawn()`]: #child_processspawncommand-args-options
+[`child_process.spawnSync()`]: #child_processspawnsynccommand-args-options
+[`maxBuffer` and Unicode]: #maxbuffer-and-unicode
+[`net.Server`]: /api/v16/net#class-netserver
+[`net.Socket`]: /api/v16/net#class-netsocket
+[`options.detached`]: #optionsdetached
+[`process.disconnect()`]: /api/v16/process#processdisconnect
+[`process.env`]: /api/v16/process#processenv
+[`process.execPath`]: /api/v16/process#processexecpath
+[`process.send()`]: /api/v16/process#processsendmessage-sendhandle-options-callback
+[`stdio`]: #optionsstdio
+[`subprocess.connected`]: #subprocessconnected
+[`subprocess.disconnect()`]: #subprocessdisconnect
+[`subprocess.kill()`]: #subprocesskillsignal
+[`subprocess.send()`]: #subprocesssendmessage-sendhandle-options-callback
+[`subprocess.stderr`]: #subprocessstderr
+[`subprocess.stdin`]: #subprocessstdin
+[`subprocess.stdio`]: #subprocessstdio
+[`subprocess.stdout`]: #subprocessstdout
+[`util.promisify()`]: /api/v16/util#utilpromisifyoriginal
+[synchronous counterparts]: #synchronous-process-creation
+[v8.serdes]: v8.md#serialization-api
diff --git a/content/api/v16/cli.en.md b/content/api/v16/cli.en.md
new file mode 100644
index 0000000000..d7eea84608
--- /dev/null
+++ b/content/api/v16/cli.en.md
@@ -0,0 +1,1817 @@
+---
+title: 'cli'
+displayTitle: 'Command-line API'
+category: 'api'
+version: 'v16'
+---
+
+
+
+
+
+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.
+
+To view this documentation as a manual page in a terminal, run `man node`.
+
+### Synopsis
+
+`node [options] [V8 options] [ | -e "script" | -] [--] [arguments]`
+
+`node inspect [ | -e "script" | :] …`
+
+`node --v8-options`
+
+Execute without arguments to start the [REPL][].
+
+For more info about `node inspect`, see the [debugger][] documentation.
+
+### Program entry point
+
+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 [CommonJS][] module loader. If no
+corresponding file is found, an error is thrown.
+
+If a file is found, its path will be passed to the [ECMAScript module loader][]
+under any of the following conditions:
+
+* The program was started with a command-line flag that forces the entry
+ point to be loaded with ECMAScript module loader.
+* The file has an `.mjs` extension.
+* The file does not have a `.cjs` extension, and the nearest parent
+ `package.json` file contains a top-level [`"type"`][] field with a value of
+ `"module"`.
+
+Otherwise, the file is loaded using the CommonJS module loader. See
+[Modules loaders][] for more details.
+
+#### ECMAScript modules loader entry point caveat
+
+When loading [ECMAScript module loader][] loads the program entry point, the `node`
+command will only accept as input only files with `.js`, `.mjs`, or `.cjs`
+extensions; and with `.wasm` extensions when
+[`--experimental-wasm-modules`][] is enabled.
+
+### Options
+
+