### Run benchmarks Source: https://github.com/nodejs/node/blob/main/deps/undici/src/CONTRIBUTING.md Installs dependencies and starts the benchmark server at http://localhost:3042. ```bash cd benchmarks && npm i && npm run bench ``` -------------------------------- ### Serve documentation locally Source: https://github.com/nodejs/node/blob/main/deps/undici/src/CONTRIBUTING.md Installs dependencies and starts the documentation server at http://localhost:3000. ```bash cd docs && npm i && npm run serve ``` -------------------------------- ### Complete SQLTagStore Usage Example (CommonJS) Source: https://github.com/nodejs/node/blob/main/doc/api/sqlite.md A comprehensive example demonstrating how to initialize `DatabaseSync` and `SQLTagStore`, then use `run`, `get`, and `all` methods with tagged literals for database operations in a CommonJS environment. ```javascript const { DatabaseSync } = require('node:sqlite'); const db = new DatabaseSync(':memory:'); const sql = db.createTagStore(); db.exec('CREATE TABLE users (id INT, name TEXT)'); // Using the 'run' method to insert data. // The tagged literal is used to identify the prepared statement. sql.run`INSERT INTO users VALUES (1, 'Alice')`; sql.run`INSERT INTO users VALUES (2, 'Bob')`; // Using the 'get' method to retrieve a single row. const name = 'Alice'; const user = sql.get`SELECT * FROM users WHERE name = ${name}`; console.log(user); // { id: 1, name: 'Alice' } // Using the 'all' method to retrieve all rows. const allUsers = sql.all`SELECT * FROM users ORDER BY id`; console.log(allUsers); // [ // { id: 1, name: 'Alice' }, // { id: 2, name: 'Bob' } // ] ``` -------------------------------- ### Install Undici fetch for consistent testing environment Source: https://github.com/nodejs/node/blob/main/deps/undici/src/docs/docs/api/GlobalInstallation.md Shows how to use `install()` in a test setup to ensure all tests utilize Undici's implementations of web APIs. This provides predictable and consistent fetch behavior across tests. ```js import { install } from 'undici' // In test setup, ensure consistent fetch behavior install() // Now all tests use undici's implementations test('fetch API test', async () => { const response = await fetch('https://example.com') expect(response).toBeInstanceOf(Response) }) ``` -------------------------------- ### Complete SQLTagStore Usage Example (ESM) Source: https://github.com/nodejs/node/blob/main/doc/api/sqlite.md A comprehensive example demonstrating how to initialize `DatabaseSync` and `SQLTagStore`, then use `run`, `get`, and `all` methods with tagged literals for database operations in an ESM environment. ```javascript import { DatabaseSync } from 'node:sqlite'; const db = new DatabaseSync(':memory:'); const sql = db.createTagStore(); db.exec('CREATE TABLE users (id INT, name TEXT)'); // Using the 'run' method to insert data. // The tagged literal is used to identify the prepared statement. sql.run`INSERT INTO users VALUES (1, 'Alice')`; sql.run`INSERT INTO users VALUES (2, 'Bob')`; // Using the 'get' method to retrieve a single row. const name = 'Alice'; const user = sql.get`SELECT * FROM users WHERE name = ${name}`; console.log(user); // { id: 1, name: 'Alice' } // Using the 'all' method to retrieve all rows. const allUsers = sql.all`SELECT * FROM users ORDER BY id`; console.log(allUsers); // [ // { id: 1, name: 'Alice' }, // { id: 2, name: 'Bob' } // ] ``` -------------------------------- ### Example npm profile get output Source: https://github.com/nodejs/node/blob/main/deps/npm/docs/output/commands/npm-profile.html Illustrates the typical information displayed when retrieving user profile details using `npm profile get`. ```text name: example email: e@example.com (verified) two-factor auth: auth-and-writes fullname: Example User homepage: freenode: twitter: github: created: 2015-02-26T01:38:35.892Z updated: 2017-10-02T21:29:45.922Z ``` -------------------------------- ### Debugging with `NODE_INSPECT_RESUME_ON_START` and `repl` Source: https://github.com/nodejs/node/blob/main/doc/api/debugger.md This example demonstrates starting the debugger to run until the first `debugger` statement, using `next` to step, and `repl` to evaluate expressions. ```console $ NODE_INSPECT_RESUME_ON_START=1 node inspect myscript.js < Debugger listening on ws://127.0.0.1:9229/f1ed133e-7876-495b-83ae-c32c6fc319c2 < For help, see: https://nodejs.org/learn/getting-started/debugging < connecting to 127.0.0.1:9229 ... ok < Debugger attached. < < hello < break in myscript.js:4 2 global.x = 5; 3 setTimeout(() => { > 4 debugger; 5 console.log('world'); 6 }, 1000); debug> next break in myscript.js:5 3 setTimeout(() => { 4 debugger; > 5 console.log('world'); 6 }, 1000); 7 console.log('hello'); debug> repl Press Ctrl+C to leave debug repl > x 5 > 2 + 2 4 debug> next < world < break in myscript.js:6 4 debugger; 5 console.log('world'); > 6 }, 1000); 7 console.log('hello'); 8 debug> .exit $ ``` -------------------------------- ### Building and Loading a Snapshot with an Entry Script (Console) Source: https://github.com/nodejs/node/blob/main/doc/api/cli.md This example demonstrates how to create a snapshot blob from an initial script and then load that snapshot with a separate entry script to access the snapshotted global state. ```console $ echo "globalThis.foo = 'I am from the snapshot'" > snapshot.js # Run snapshot.js to initialize the application and snapshot the # state of it into snapshot.blob. $ node --snapshot-blob snapshot.blob --build-snapshot snapshot.js $ echo "console.log(globalThis.foo)" > index.js # Load the generated snapshot and start the application from index.js. $ node --snapshot-blob snapshot.blob index.js I am from the snapshot ``` -------------------------------- ### Build c-ares on Windows with MSVC using CMake and NMake Source: https://github.com/nodejs/node/blob/main/deps/cares/INSTALL.md This example details how to build and install c-ares on Windows using the Microsoft Visual C++ (MSVC) command-line tools, CMake, and the NMake Makefiles generator. It sets the build type to Release and defines the installation directory for the compiled library. ```cmd cd \path\to\cmake\source mkdir build cd build cmake -DCMAKE_BUILD_TYPE=Release -DCMAKE_INSTALL_PREFIX=C:\cares -G "NMake Makefiles" .. nmake nmake install ``` -------------------------------- ### repl.start([options]) Source: https://github.com/nodejs/node/blob/main/doc/api/repl.md Creates and starts a `repl.REPLServer` instance. The `options` argument can be a configuration object or a string to set the input prompt. ```APIDOC ## `repl.start([options])` ### Description The `repl.start()` method creates and starts a [`repl.REPLServer`][] instance. ### Signature `repl.start([options])` ### Parameters - **options** (object | string) - Optional - Configuration options for the REPL server. If a string, it specifies the input prompt. - If `options` is an object, it can contain properties for error handling: - **ignore** (string) - When set, skips all remaining error handling. - **unhandled** (string) - When set, treats the exception as fully unhandled, passing it to process-wide exception handlers (e.g., the [`'uncaughtException'`][] event). ### Returns - **{repl.REPLServer}** - A new `repl.REPLServer` instance. ### Examples #### Using a string for prompt ```mjs import repl from 'node:repl'; // a Unix style prompt repl.start('$ '); ``` ```cjs const repl = require('node:repl'); // a Unix style prompt repl.start('$ '); ``` ``` -------------------------------- ### Example Error Handling Without Suggestions in Commander.js (Console) Source: https://github.com/nodejs/node/blob/main/test/fixtures/postject-copy/node_modules/commander/Readme.md This console output illustrates the behavior when spelling suggestions are disabled after an error. It shows only the error message without any 'Did you mean?' prompts. ```console $ pizza --hepl error: unknown option '--hepl' ``` -------------------------------- ### Environment File Comments (Text) Source: https://github.com/nodejs/node/blob/main/doc/api/cli.md Shows how to include comments in an environment file using the hash symbol (`#`), which can appear at the start of a line or after a value. ```text # This is a comment PORT=3000 # This is also a comment ``` -------------------------------- ### Example Error Handling with Help Display in Commander.js (Console) Source: https://github.com/nodejs/node/blob/main/test/fixtures/postject-copy/node_modules/commander/Readme.md This console output demonstrates the effect of `showHelpAfterError` when an unknown option is provided. It shows the error message followed by the custom help prompt. ```console $ pizza --unknown error: unknown option '--unknown' (add --help for additional information) ``` -------------------------------- ### Instantiating REPLServer Source: https://github.com/nodejs/node/blob/main/doc/api/repl.md Shows two ways to create a 'repl.REPLServer' instance: using 'repl.start()' and directly with 'new repl.REPLServer()'. Both methods accept an options object for configuration. ```mjs import repl from 'node:repl'; const options = { useColors: true }; const firstInstance = repl.start(options); const secondInstance = new repl.REPLServer(options); ``` ```cjs const repl = require('node:repl'); const options = { useColors: true }; const firstInstance = repl.start(options); const secondInstance = new repl.REPLServer(options); ``` -------------------------------- ### Start Node.js CPU Profiling with Default and Custom Naming Source: https://github.com/nodejs/node/blob/main/doc/api/cli.md Initiates V8 CPU profiling for a Node.js application, demonstrating both default profile naming and custom naming using the `--cpu-prof-name` flag. Profiles are saved to disk before exit. ```bash $ node --cpu-prof index.js $ ls *.cpuprofile CPU.20190409.202950.15293.0.0.cpuprofile ``` ```bash $ node --cpu-prof --cpu-prof-name 'CPU.${pid}.cpuprofile' index.js $ ls *.cpuprofile CPU.15293.cpuprofile ``` -------------------------------- ### Help Display Methods Source: https://github.com/nodejs/node/blob/main/test/fixtures/postject-copy/node_modules/commander/Readme.md Methods for displaying help information in various ways. Use .help() to display and exit, .outputHelp() to display without exiting, or .helpInformation() to get the help text as a string for custom processing. ```APIDOC ## Help Display Methods ### Description Provides methods to display help information with different behaviors for exiting and output destination. ### Methods #### .help(options) Display help information and exit immediately. **Parameters:** - **options** (object) - Optional - **error** (boolean) - Optional - If true, display on stderr and exit with error status **Example:** ```js program.help(); program.help({ error: true }); ``` #### .outputHelp(options) Output help information without exiting the process. **Parameters:** - **options** (object) - Optional - **error** (boolean) - Optional - If true, display on stderr instead of stdout **Example:** ```js program.outputHelp(); program.outputHelp({ error: true }); ``` #### .helpInformation() Get the built-in command help information as a string for processing or displaying yourself. **Returns:** - **string** - The help information text **Example:** ```js const helpText = program.helpInformation(); console.log(helpText); ``` ``` -------------------------------- ### Run Node.js with Watch Mode Source: https://github.com/nodejs/node/blob/main/doc/api/cli.md Starts Node.js in watch mode, automatically restarting the process when changes are detected in the entry point or its required/imported modules. ```bash node --watch index.js ``` -------------------------------- ### Serve Documentation Locally Source: https://github.com/nodejs/node/blob/main/BUILDING.md Start a static file server to browse the generated documentation in a web browser, providing a local URL. ```bash make docserve ``` -------------------------------- ### Example Custom Help Output in Commander.js (Text) Source: https://github.com/nodejs/node/blob/main/test/fixtures/postject-copy/node_modules/commander/Readme.md This text output shows the result of adding custom help text using `addHelpText` in Commander.js. It illustrates how the custom content is integrated into the standard help message. ```Text Usage: custom-help [options] Options: -f, --foo enable some foo -h, --help display help for command Example call: $ custom-help --help ``` -------------------------------- ### v8.startCpuProfile([options]) Source: https://github.com/nodejs/node/blob/main/doc/api/v8.md Starts a CPU profile and returns a `SyncCPUProfileHandle` object. This API supports `using` syntax. ```APIDOC ## v8.startCpuProfile([options]) ### Description Starts a CPU profile then returns a `SyncCPUProfileHandle` object. This API supports `using` syntax. ### Method N/A (Static method) ### Endpoint N/A ### Parameters #### Function Parameters - **options** (Object) - Optional - Configuration options for the CPU profile. - **sampleInterval** (number) - Optional - Requested sampling interval in milliseconds. Default: `0`. - **maxBufferSize** (integer) - Optional - Maximum number of samples to keep before older entries are discarded. Default: `4294967295`. ### Request Body N/A ### Response #### Success Response - **SyncCPUProfileHandle** (SyncCPUProfileHandle) - An object to manage the CPU profile. #### Request Example ```cjs const handle = v8.startCpuProfile({ sampleInterval: 1, maxBufferSize: 10_000 }); const profile = handle.stop(); console.log(profile); ``` ``` -------------------------------- ### Disable Spelling Suggestions After Errors in Commander.js (JavaScript) Source: https://github.com/nodejs/node/blob/main/test/fixtures/postject-copy/node_modules/commander/Readme.md This JavaScript example demonstrates how to disable Commander.js's default behavior of suggesting correct spelling for unknown commands or options after an error, providing more control over error messages. ```js program.showSuggestionAfterError(false); ``` -------------------------------- ### Define Stand-alone Executable Subcommands with Commander.js (JavaScript) Source: https://github.com/nodejs/node/blob/main/test/fixtures/postject-copy/node_modules/commander/Readme.md This JavaScript example demonstrates how to define subcommands that map to external executable files using Commander.js. It shows how to specify a custom executable file name and how to designate a default subcommand. ```js program .name('pm') .version('0.1.0') .command('install [name]', 'install one or more packages') .command('search [query]', 'search with optional query') .command('update', 'update installed packages', { executableFile: 'myUpdateSubCommand' }) .command('list', 'list packages installed', { isDefault: true }); program.parse(process.argv); ``` -------------------------------- ### Example: Prepare Node.js v20.x Release Source: https://github.com/nodejs/node/blob/main/doc/contributing/releases.md An example demonstrating how to check out a specific release line and then prepare a release with security and label filtering. ```bash git checkout v20.x git node release -S --prepare --security=../vulnerabilities.json --filterLabel v20.x ``` -------------------------------- ### Display Automated Help for Commander.js CLI (Console) Source: https://github.com/nodejs/node/blob/main/test/fixtures/postject-copy/node_modules/commander/Readme.md This console example shows the auto-generated help information provided by Commander.js for a command-line interface. It demonstrates how to invoke help using the `--help` option, displaying usage, options, and descriptions. ```console $ node ./examples/pizza --help Usage: pizza [options] An application for pizza ordering Options: -p, --peppers Add peppers -c, --cheese Add the specified type of cheese (default: "marble") -C, --no-cheese You do not want any cheese -h, --help display help for command ``` -------------------------------- ### Implementing vm.Module Lifecycle (ESM and CJS) Source: https://github.com/nodejs/node/blob/main/doc/api/vm.md This example illustrates the three-step process of using `vm.Module`: creating a module, linking its dependencies, and evaluating it within a VM context. This functionality is experimental and requires a specific command flag. ```JavaScript (ESM) import vm from 'node:vm'; const contextifiedObject = vm.createContext({ secret: 42, print: console.log, }); // Step 1 // // Create a Module by constructing a new `vm.SourceTextModule` object. This // parses the provided source text, throwing a `SyntaxError` if anything goes // wrong. By default, a Module is created in the top context. But here, we // specify `contextifiedObject` as the context this Module belongs to. // // Here, we attempt to obtain the default export from the module "foo", and // put it into local binding "secret". const rootModule = new vm.SourceTextModule(` import s from 'foo'; s; print(s); `, { context: contextifiedObject }); // Step 2 // // "Link" the imported dependencies of this Module to it. // // Obtain the requested dependencies of a SourceTextModule by // `sourceTextModule.moduleRequests` and resolve them. // // Even top-level Modules without dependencies must be explicitly linked. The // array passed to `sourceTextModule.linkRequests(modules)` can be // empty, however. // // Note: This is a contrived example in that the resolveAndLinkDependencies // creates a new "foo" module every time it is called. In a full-fledged // module system, a cache would probably be used to avoid duplicated modules. const moduleMap = new Map([ ['root', rootModule], ]); function resolveAndLinkDependencies(module) { const requestedModules = module.moduleRequests.map((request) => { // In a full-fledged module system, the resolveAndLinkDependencies would // resolve the module with the module cache key `[specifier, attributes]`. // In this example, we just use the specifier as the key. const specifier = request.specifier; let requestedModule = moduleMap.get(specifier); if (requestedModule === undefined) { requestedModule = new vm.SourceTextModule(` // The "secret" variable refers to the global variable we added to // "contextifiedObject" when creating the context. export default secret; `, { context: module.context }); moduleMap.set(specifier, requestedModule); // Resolve the dependencies of the new module as well. resolveAndLinkDependencies(requestedModule); } return requestedModule; }); module.linkRequests(requestedModules); } resolveAndLinkDependencies(rootModule); rootModule.instantiate(); // Step 3 // // Evaluate the Module. The evaluate() method returns a promise which will // resolve after the module has finished evaluating. // Prints 42. await rootModule.evaluate(); ``` ```JavaScript (CJS) const vm = require('node:vm'); const contextifiedObject = vm.createContext({ secret: 42, print: console.log, }); (async () => { // Step 1 // // Create a Module by constructing a new `vm.SourceTextModule` object. This // parses the provided source text, throwing a `SyntaxError` if anything goes // wrong. By default, a Module is created in the top context. But here, we // specify `contextifiedObject` as the context this Module belongs to. // // Here, we attempt to obtain the default export from the module "foo", and // put it into local binding "secret". const rootModule = new vm.SourceTextModule(` import s from 'foo'; s; print(s); `, { context: contextifiedObject }); // Step 2 // // "Link" the imported dependencies of this Module to it. // // Obtain the requested dependencies of a SourceTextModule by // `sourceTextModule.moduleRequests` and resolve them. // // Even top-level Modules without dependencies must be explicitly linked. The // array passed to `sourceTextModule.linkRequests(modules)` can be // empty, however. // // Note: This is a contrived example in that the resolveAndLinkDependencies // creates a new "foo" module every time it is called. In a full-fledged // module system, a cache would probably be used to avoid duplicated modules. const moduleMap = new Map([ ['root', rootModule], ]); function resolveAndLinkDependencies(module) { const requestedModules = module.moduleRequests.map((request) => { // In a full-fledged module system, the resolveAndLinkDependencies would ``` -------------------------------- ### Add Custom Help Text to Commander.js Commands (JavaScript) Source: https://github.com/nodejs/node/blob/main/test/fixtures/postject-copy/node_modules/commander/Readme.md This JavaScript example demonstrates how to add extra text to the built-in help output of a Commander.js program. The `addHelpText` method allows specifying content and position (e.g., 'after') for custom information. ```js program .option('-f, --foo', 'enable some foo'); program.addHelpText('after', ` Example call: $ custom-help --help`); ``` -------------------------------- ### Set Up Global State for Benchmarks Source: https://github.com/nodejs/node/blob/main/doc/contributing/writing-and-running-benchmarks.md The `setup` option allows running a function once in the root process before benchmark combinations are executed in child processes, useful for initializing global state or resources. Note that JavaScript heap state is not shared with child processes. ```js const tmpdir = require('../../test/common/tmpdir'); const bench = common.createBenchmark(main, { type: ['fast', 'slow'], n: [1e4] }, { setup(configs) { tmpdir.refresh(); const maxN = configs.reduce((max, c) => Math.max(max, c.n), 0); setupFixturesReusedForAllBenchmarks(maxN); } }); ``` -------------------------------- ### Evaluate JavaScript from CLI (Bash) Source: https://github.com/nodejs/node/blob/main/doc/api/cli.md Executes a JavaScript string directly from the command line using `--eval`, with predefined REPL modules available. Use `=` for scripts starting with `-`. ```bash node --print --eval=-42 ``` -------------------------------- ### Prepare project with package-lock.json Source: https://github.com/nodejs/node/blob/main/deps/npm/docs/content/commands/npm-ci.md Demonstrates preparing a project by navigating to its directory, installing dependencies to generate a `package-lock.json`, and verifying its creation. ```bash $ cd ./my/npm/project $ npm install added 154 packages in 10s $ ls | grep package-lock ``` -------------------------------- ### Verify gyp-next installation output Source: https://github.com/nodejs/node/blob/main/tools/gyp/README.md Example output from a successful gyp-next installation via pipx, showing the installed version, Python version, and available global commands. ```bash Installing to a new venv 'gyp-next' installed package gyp-next 0.13.0, installed using Python 3.10.6 These apps are now globally available - gyp done! ✨ 🌟 ✨ ``` -------------------------------- ### Start Local Development Webserver for V8 Tools Source: https://github.com/nodejs/node/blob/main/deps/v8/tools/README.md Sets up a local webserver on localhost:8000 for V8 tools development. Requires Node.js and npm installed. Installs dependencies and starts the development server. ```bash cd tools/; npm install; npm run start-webserver; ``` -------------------------------- ### Setup WPT testing environment Source: https://github.com/nodejs/node/blob/main/deps/undici/src/CONTRIBUTING.md Prepares the environment before running web-platform-tests for the first time. ```bash cd test/web-platform-tests node wpt-runner.mjs setup ``` -------------------------------- ### v8.startHeapProfile([options]) Source: https://github.com/nodejs/node/blob/main/doc/api/v8.md Starts a heap profile and returns a `SyncHeapProfileHandle` object. This API supports `using` syntax. ```APIDOC ## Method: v8.startHeapProfile([options]) ### Description Starts a heap profile then return a `SyncHeapProfileHandle` object. This API supports `using` syntax. ### Parameters - **options** (Object) - Optional - Configuration options for the heap profile. - **sampleInterval** (number) - Optional - The average sampling interval in bytes. Default: `524288` (512 KiB). - **stackDepth** (integer) - Optional - The maximum stack depth for samples. Default: `16`. - **forceGC** (boolean) - Optional - Force garbage collection before taking the profile. Default: `false`. - **includeObjectsCollectedByMajorGC** (boolean) - Optional - Include objects collected by major GC. Default: `false`. - **includeObjectsCollectedByMinorGC** (boolean) - Optional - Include objects collected by minor GC. Default: `false`. ### Returns - **SyncHeapProfileHandle** - An object to manage the heap profile. ### Examples #### Basic Usage ```javascript const v8 = require('node:v8'); const handle = v8.startHeapProfile(); const profile = handle.stop(); console.log(profile); ``` ```javascript import v8 from 'node:v8'; const handle = v8.startHeapProfile(); const profile = handle.stop(); console.log(profile); ``` #### With Custom Parameters ```javascript const v8 = require('node:v8'); const handle = v8.startHeapProfile({ sampleInterval: 1024, stackDepth: 8, forceGC: true, includeObjectsCollectedByMajorGC: true, }); const profile = handle.stop(); console.log(profile); ``` ```javascript import v8 from 'node:v8'; const handle = v8.startHeapProfile({ sampleInterval: 1024, stackDepth: 8, forceGC: true, includeObjectsCollectedByMajorGC: true, }); const profile = handle.stop(); console.log(profile); ``` ``` -------------------------------- ### Install OpenSSL HTML Documentation with Make Source: https://github.com/nodejs/node/blob/main/deps/openssl/openssl/INSTALL.md This `make` target installs only the HTML documentation for OpenSSL. This provides browser-viewable documentation for the project. ```shell make install_html_docs ``` -------------------------------- ### Example project structure with workspaces Source: https://github.com/nodejs/node/blob/main/deps/npm/docs/output/commands/npm-run.html Illustrates a typical project layout with a root `package.json` and multiple nested workspace packages. ```text . +-- package.json `-- packages +-- a | `-- package.json +-- b | `-- package.json `-- c `-- package.json ``` -------------------------------- ### Example HTTP GET Request Source: https://github.com/nodejs/node/blob/main/doc/api/http.md This snippet shows a basic HTTP GET request for `/status?name=ryan` with an `Accept` header. ```http GET /status?name=ryan HTTP/1.1 Accept: text/plain ``` -------------------------------- ### npm start command line synopsis Source: https://github.com/nodejs/node/blob/main/deps/npm/docs/output/commands/npm-start.html Use this syntax to run the npm start command, optionally passing arguments to the underlying script. ```bash npm start [-- ] ``` -------------------------------- ### Install OpenSSL Documentation Components with Make Source: https://github.com/nodejs/node/blob/main/deps/openssl/openssl/INSTALL.md This `make` target installs only the documentation components of OpenSSL, such as man pages or HTML files. It's used when the software is already installed or not required. ```shell make install_docs ``` -------------------------------- ### npm edit example - Edit connect package Source: https://github.com/nodejs/node/blob/main/deps/npm/docs/content/commands/npm-edit.md Practical example showing how to install the connect package and then edit it locally. First installs connect as a dependency, then opens it in the editor for modifications. The package is rebuilt automatically after editing to incorporate any changes. ```bash npm install connect npm edit connect ``` -------------------------------- ### Install Packages with Dependency Save Options and Targets Source: https://github.com/nodejs/node/blob/main/deps/npm/docs/content/commands/npm-install.md Demonstrates installing packages with different flags to control how they are saved in `package.json`, such as production, development, optional, peer, exact, or bundled dependencies, and installing from various sources like GitHub repositories or scoped packages. ```bash npm install sax ``` ```bash npm install githubname/reponame ``` ```bash npm install @myorg/privatepackage ``` ```bash npm install node-tap --save-dev ``` ```bash npm install dtrace-provider --save-optional ``` ```bash npm install readable-stream --save-exact ``` ```bash npm install ansi-regex --save-bundle ``` -------------------------------- ### Install OpenSSL Software Components with Make Source: https://github.com/nodejs/node/blob/main/deps/openssl/openssl/INSTALL.md This `make` target installs only the software components of OpenSSL, excluding any documentation. It's useful when only the executables and libraries are needed. ```shell make install_sw ``` -------------------------------- ### Define Variadic Options in Commander.js Source: https://github.com/nodejs/node/blob/main/test/fixtures/postject-copy/node_modules/commander/Readme.md Create variadic options by appending `...` to the value placeholder, allowing multiple option-arguments to be parsed into an array. Values are read until the first dash-prefixed argument, with `--` stopping all option processing. This example demonstrates both required and optional variadic options. ```javascript program .option('-n, --number ', 'specify numbers') .option('-l, --letter [letters...]', 'specify letters'); program.parse(); console.log('Options: ', program.opts()); console.log('Remaining arguments: ', program.args); ``` -------------------------------- ### Commander.js Option Argument Syntax Examples Source: https://github.com/nodejs/node/blob/main/test/fixtures/postject-copy/node_modules/commander/Readme.md This shell snippet demonstrates various ways to specify option arguments when using Commander.js. It shows that arguments can be separated by a space, directly follow a short option, or follow an equals sign for a long option, providing flexibility in command-line input. ```sh serve -p 80 serve -p80 serve --port 80 serve --port=80 ``` -------------------------------- ### server.listen(options[, callback]) Source: https://github.com/nodejs/node/blob/main/doc/api/net.md Starts a server listening for connections using a detailed options object, allowing for configuration of host, port, path, exclusive mode, and more. ```APIDOC ## server.listen(options[, callback]) ### Description Starts a server listening for connections using a detailed options object. ### Parameters - **options** (Object) - Required - Supports various properties for server configuration. - **backlog** (number) - Optional - Common parameter of `server.listen()` functions. - **exclusive** (boolean) - Optional - Default: `false`. If `true`, the handle is not shared among cluster workers. - **handle** (net.BoundSocket) - Optional - A pre-bound `BoundSocket` for the server to adopt. The server adopts the already-bound socket and listens on it, ignoring `host`, `port`, and `path`. - **host** (string) - Optional - The host to listen on. - **ipv6Only** (boolean) - Optional - Default: `false`. For TCP servers, setting `ipv6Only` to `true` will disable dual-stack support. - **reusePort** (boolean) - Optional - Default: `false`. For TCP servers, allows multiple sockets on the same host to bind to the same port. This option is available only on some platforms. - **path** (string) - Optional - Path for IPC connections. Will be ignored if `port` is specified. - **port** (number) - Optional - The port to listen on. - **readableAll** (boolean) - Optional - Default: `false`. For IPC servers, makes the pipe readable for all users. - **signal** (AbortSignal) - Optional - An `AbortSignal` that may be used to close a listening server. - **writableAll** (boolean) - Optional - Default: `false`. For IPC servers, makes the pipe writable for all users. - **callback** (Function) - Optional - A callback function. ### Request Example ```js server.listen({ host: 'localhost', port: 80, exclusive: true }); ``` ```js const controller = new AbortController(); server.listen({ host: 'localhost', port: 80, signal: controller.signal }); // Later, when you want to close the server. controller.abort(); ``` ### Response - Returns: {net.Server} ``` -------------------------------- ### Install Packages from GitHub Shorthand Source: https://github.com/nodejs/node/blob/main/deps/npm/docs/content/commands/npm-install.md Shows how to install packages from GitHub repositories using simplified `user/repo` or `github:user/repo` syntax. ```bash npm install mygithubuser/myproject ``` ```bash npm install github:mygithubuser/myproject ``` -------------------------------- ### Store Options as Properties in Commander.js Source: https://github.com/nodejs/node/blob/main/test/fixtures/postject-copy/node_modules/commander/Readme.md Demonstrates how to revert to pre-Commander 7 behavior where option values are stored as properties on the command object. This enables legacy code compatibility but may cause property name clashes. The example shows checking a debug option and logging the command name when enabled. ```javascript program .storeOptionsAsProperties() .option('-d, --debug') .action((commandAndOptions) => { if (commandAndOptions.debug) { console.error(`Called ${commandAndOptions.name()}`); } }); ``` -------------------------------- ### Install Acorn from source Source: https://github.com/nodejs/node/blob/main/deps/acorn/acorn/README.md Clone the Acorn repository, navigate into the directory, and install its dependencies. ```sh git clone https://github.com/acornjs/acorn.git cd acorn npm install ``` -------------------------------- ### Approve npm install scripts Source: https://github.com/nodejs/node/blob/main/deps/npm/docs/content/commands/npm-approve-scripts.md Examples demonstrating how to approve install scripts for all currently-installed packages, specific packages, or preview which packages still need review. ```bash # Approve all currently-installed install scripts after reviewing them npm approve-scripts --all ``` ```bash # Approve specific packages, pinned to their installed version npm approve-scripts canvas sharp ``` ```bash # Approve name-only (any version of this package is allowed) npm approve-scripts --no-allow-scripts-pin canvas ``` ```bash # Preview which packages still need review npm approve-scripts --allow-scripts-pending ``` -------------------------------- ### Example Command-Line Arguments and Output Source: https://github.com/nodejs/node/blob/main/doc/api/process.md Demonstrates how command-line arguments are parsed and appear in `process.argv` when a script is executed. ```bash node process-args.js one two=three four ``` ```text 0: /usr/local/bin/node 1: /Users/mjr/work/node/process-args.js 2: one 3: two=three 4: four ``` -------------------------------- ### Install OpenSSL Man Pages on Unix with Make Source: https://github.com/nodejs/node/blob/main/deps/openssl/openssl/INSTALL.md On Unix systems, this `make` target specifically installs only the OpenSSL man pages. This allows users to access documentation through the `man` command. ```shell make install_man_docs ``` -------------------------------- ### Install Packages from Git URLs Source: https://github.com/nodejs/node/blob/main/deps/npm/docs/content/commands/npm-install.md Demonstrates installing packages from Git repositories using different protocols, commit references, and SSH configurations. ```bash npm install git+ssh://git@github.com:npm/cli.git#v1.0.27 ``` ```bash npm install git+ssh://git@github.com:npm/cli#pull/273 ``` ```bash npm install git+ssh://git@github.com:npm/cli#semver:^5.0 ``` ```bash npm install git+https://isaacs@github.com/npm/cli.git ``` ```bash npm install git://github.com/npm/cli.git#v1.0.27 ``` ```bash GIT_SSH_COMMAND='ssh -i ~/.ssh/custom_ident' npm install git+ssh://git@github.com:npm/cli.git ``` -------------------------------- ### Uninstall All OpenSSL Components with Make Source: https://github.com/nodejs/node/blob/main/deps/openssl/openssl/INSTALL.md This `make` target removes all installed OpenSSL components from the system. It performs a complete uninstallation of the project. ```shell make uninstall ``` -------------------------------- ### Execute 'start' script with npm start Source: https://github.com/nodejs/node/blob/main/deps/npm/docs/output/commands/npm-start.html Run the npm start command to execute the 'start' script defined in package.json and view its output. ```bash npm start > npm@x.x.x start > node foo.js (foo.js output would be here) ``` -------------------------------- ### Install OpenSSL on OpenVMS Source: https://github.com/nodejs/node/blob/main/deps/openssl/openssl/INSTALL.md This snippet provides the command to install OpenSSL on OpenVMS systems. The `mms install` command is executed to place OpenSSL files into the default location, `SYS$COMMON:[OPENSSL]`. This process typically requires appropriate system privileges. ```bash mms install ``` -------------------------------- ### Configure Commander.js output and error display in Node.js Source: https://github.com/nodejs/node/blob/main/test/fixtures/postject-copy/node_modules/commander/Readme.md This example shows how to customize Commander.js's output streams and error message formatting using `configureOutput()`. It overrides `writeOut` and `writeErr` to prefix messages and uses a helper function `errorColor` to display error messages in red using ANSI escape codes. ```javascript function errorColor(str) { // Add ANSI escape codes to display text in red. return `\x1b[31m${str}\x1b[0m`; } program .configureOutput({ // Visibly override write routines as example! writeOut: (str) => process.stdout.write(`[OUT] ${str}`), writeErr: (str) => process.stdout.write(`[ERR] ${str}`), // Highlight errors in color. outputError: (str, write) => write(errorColor(str)) }); ``` -------------------------------- ### Commander.js Subcommand Help and Execution Example Source: https://github.com/nodejs/node/blob/main/test/fixtures/postject-copy/node_modules/commander/Readme.md This console output demonstrates interacting with a Commander.js CLI that uses subcommands. The first command shows the generated help message for the `split` subcommand, detailing its usage, arguments, and options. The second command executes the `split` subcommand, splitting 'a/b/c' by '/' and displaying the result. ```console $ node string-util.js help split Usage: string-util split [options] Split a string into substrings and display as an array. Arguments: string string to split Options: --first display just the first substring -s, --separator separator character (default: ",") -h, --help display help for command $ node string-util.js split --separator=/ a/b/c [ 'a', 'b', 'c' ] ``` -------------------------------- ### Complete Node.js Benchmark Example Source: https://github.com/nodejs/node/blob/main/doc/contributing/writing-and-running-benchmarks.md This comprehensive example demonstrates how to define benchmark configurations, specify Node.js command-line flags, and implement the `main` function to perform operations and time their execution using `bench.start()` and `bench.end(n)`. ```js const common = require('../common.js'); const { Buffer } = require('node:buffer'); const configs = { // Number of operations, specified here so they show up in the report. // Most benchmarks just use one value for all runs. n: [1024], type: ['fast', 'slow'], // Custom configurations size: [16, 128, 1024] // Custom configurations }; const options = { // Add --expose-internals in order to require internal modules in main flags: ['--zero-fill-buffers'] }; // `main` and `configs` are required, `options` is optional. const bench = common.createBenchmark(main, configs, options); // Any code outside main will be run twice, // in different processes, with different command line arguments. function main(conf) { // Only flags that have been passed to createBenchmark // earlier when main is run will be in effect. // In order to benchmark the internal modules, require them here. For example: // const URL = require('internal/url').URL // Start the timer bench.start(); // Do operations here for (let i = 0; i < conf.n; i++) { conf.type === 'fast' ? Buffer.allocUnsafe(conf.size) : Buffer.allocUnsafeSlow(conf.size); } // End the timer, pass in the number of operations bench.end(conf.n); } ``` -------------------------------- ### Configure Android ARM with NDK 10d Standalone Installation Source: https://github.com/nodejs/node/blob/main/deps/openssl/openssl/NOTES-ANDROID.md Configures the build for Android ICS (API level 14) on ARM architecture using NDK 10d with GCC toolchain. This example demonstrates the older NDK structure where GCC is located in the common prebuilt tools directory rather than the llvm-specific path. ```bash export ANDROID_NDK_ROOT=/some/where/android-ndk-10d PATH=$ANDROID_NDK_ROOT/toolchains/arm-linux-androideabi-4.8/prebuilt/linux-x86_64/bin:$PATH ./Configure android-arm -D__ANDROID_API__=14 make ```