### npm install script example Source: https://github.com/asana/node/blob/main/deps/npm/docs/content/using-npm/scripts.md This JSON shows how dependencies and scripts are defined in package.json. The 'start' script executes the 'bar' executable from the 'bar' dependency. ```json { "name" : "foo", "dependencies" : { "bar" : "0.1.x" }, "scripts": { "start" : "bar ./test" } } ``` -------------------------------- ### Example npm ci usage Source: https://github.com/asana/node/blob/main/deps/npm/docs/content/commands/npm-ci.md Demonstrates the typical workflow of running npm install followed by npm ci in a project directory. This ensures dependencies are up-to-date and then performs a clean install. ```bash cd ./my/npm/project npm install added 154 packages in 10s ls | grep package-lock npm ci added 154 packages in 5s ``` -------------------------------- ### HTTP Benchmark Setup Source: https://github.com/asana/node/blob/main/doc/contributing/writing-and-running-benchmarks.md Sets up an HTTP benchmark using `bench.http`. It defines configurations for data size and connections, and the `main` function starts an HTTP server and then runs the benchmark against it. ```javascript 'use strict'; const common = require('../common.js'); const bench = common.createBenchmark(main, { kb: [64, 128, 256, 1024], connections: [100, 500], duration: 5, }); function main(conf) { const http = require('node:http'); const len = conf.kb * 1024; const chunk = Buffer.alloc(len, 'x'); const server = http.createServer((req, res) => { res.end(chunk); }); server.listen(common.PORT, () => { bench.http({ connections: conf.connections, }, () => { server.close(); }); }); } ``` -------------------------------- ### Start Local Webserver for V8 Tools Source: https://github.com/asana/node/blob/main/deps/v8/tools/README.md Run this command to start a local webserver for local development of V8 tools. Ensure you are in the tools directory and have installed dependencies. ```bash cd tools/ npm install ws ``` -------------------------------- ### Out-of-Tree Build Setup (Unix) Source: https://github.com/asana/node/blob/main/deps/openssl/openssl/INSTALL.md Prepare a separate directory for building OpenSSL to keep the source tree clean. This example shows the steps for a Unix-like system. ```bash $ mkdir /var/tmp/openssl-build $ cd /var/tmp/openssl-build $ /PATH/TO/OPENSSL/SOURCE/Configure [[ options ]] ``` -------------------------------- ### Install libuv with vcpkg Source: https://github.com/asana/node/blob/main/deps/uv/README.md Instructions for installing libuv using vcpkg. This involves cloning the vcpkg repository, bootstrapping it, and then installing libuv. ```bash $ git clone https://github.com/microsoft/vcpkg.git $ ./bootstrap-vcpkg.bat # for powershell $ ./bootstrap-vcpkg.sh # for bash $ ./vcpkg install libuv ``` -------------------------------- ### repl.start([options]) Source: https://github.com/asana/node/blob/main/doc/api/repl.md Creates and starts a `repl.REPLServer` instance. The `options` parameter can be an object to configure the REPL or a string to set the input prompt. ```APIDOC ## `repl.start([options])` * `options` {Object|string} * `prompt` {string} The input prompt to display. **Default:** `'> '` (with a trailing space). * `input` {stream.Readable} The `Readable` stream from which REPL input will be read. **Default:** `process.stdin`. * `output` {stream.Writable} The `Writable` stream to which REPL output will be written. **Default:** `process.stdout`. * `terminal` {boolean} If `true`, specifies that the `output` should be treated as a TTY terminal. **Default:** checking the value of the `isTTY` property on the `output` stream upon instantiation. * `eval` {Function} The function to be used when evaluating each given line of input. **Default:** an async wrapper for the JavaScript `eval()` function. An `eval` function can error with `repl.Recoverable` to indicate the input was incomplete and prompt for additional lines. * `useColors` {boolean} If `true`, specifies that the default `writer` function should include ANSI color styling to REPL output. If a custom `writer` function is provided then this has no effect. **Default:** checking color support on the `output` stream if the REPL instance's `terminal` value is `true`. * `useGlobal` {boolean} If `true`, specifies that the default evaluation function will use the JavaScript `global` as the context as opposed to creating a new separate context for the REPL instance. The node CLI REPL sets this value to `true`. **Default:** `false`. * `ignoreUndefined` {boolean} If `true`, specifies that the default writer will not output the return value of a command if it evaluates to `undefined`. **Default:** `false`. * `writer` {Function} The function to invoke to format the output of each command before writing to `output`. **Default:** [`util.inspect()`]. * `completer` {Function} An optional function used for custom Tab auto completion. See [`readline.InterfaceCompleter`]. * `replMode` {symbol} A flag that specifies whether the default evaluator executes all JavaScript commands in strict mode or default (sloppy) mode. Acceptable values are: * `repl.REPL_MODE_SLOPPY` to evaluate expressions in sloppy mode. * `repl.REPL_MODE_STRICT` to evaluate expressions in strict mode. This is equivalent to prefacing every repl statement with `'use strict'`. * `breakEvalOnSigint` {boolean} Stop evaluating the current piece of code when `SIGINT` is received, such as when Ctrl+C is pressed. This cannot be used together with a custom `eval` function. **Default:** `false`. * `preview` {boolean} Defines if the repl prints autocomplete and output previews or not. **Default:** `true` with the default eval function and `false` in case a custom eval function is used. If `terminal` is falsy, then there are no previews and the value of `preview` has no effect. * Returns: {repl.REPLServer} If `options` is a string, then it specifies the input prompt: ```javascript const repl = require('node:repl'); // a Unix style prompt repl.start('$ '); ``` ``` -------------------------------- ### Install Chalk Source: https://github.com/asana/node/blob/main/tools/node_modules/eslint/node_modules/@babel/highlight/node_modules/chalk/readme.md Install Chalk using npm. This is the basic setup required before using the library. ```bash $ npm install chalk ``` -------------------------------- ### Install from Tarball URL Source: https://github.com/asana/node/blob/main/deps/npm/docs/content/commands/npm-install.md Fetches and installs a package from a tarball URL. The URL must start with `http://` or `https://`. ```bash npm install https://github.com/indexzero/forever/tarball/v0.5.6 ``` -------------------------------- ### Application build.info Example Source: https://github.com/asana/node/blob/main/deps/openssl/openssl/Configurations/README-design.md Defines a program to be built, its source file, include paths, and library dependencies from the application's directory. ```makefile # apps/build.info PROGRAMS=openssl SOURCE[openssl]=openssl.c INCLUDE[openssl]=.. ../include DEPEND[openssl]=../libssl ``` -------------------------------- ### Get parent module path Source: https://github.com/asana/node/blob/main/tools/node_modules/eslint/node_modules/parent-module/readme.md Require the module and call the function to get the immediate parent's path. This example demonstrates basic usage within a module. ```javascript // bar.js const parentModule = require('parent-module'); module.exports = () => { console.log(parentModule()); //=> '/Users/sindresorhus/dev/unicorn/foo.js' }; ``` ```javascript // foo.js const bar = require('./bar'); bar(); ``` -------------------------------- ### Example: Explaining 'find-up' in a Specific Folder Source: https://github.com/asana/node/blob/main/deps/npm/docs/content/commands/npm-explain.md This example shows the output of explaining the 'find-up' package located within `node_modules/nyc/node_modules/find-up`, illustrating its dependency chain originating from the 'tap' package. ```bash find-up@3.0.0 dev node_modules/nyc/node_modules/find-up find-up@"^3.0.0" from nyc@14.1.1 node_modules/nyc nyc@"^14.1.1" from tap@14.10.8 node_modules/tap dev tap@"^14.10.8" from the root project ``` -------------------------------- ### Service Worker Installation and Communication Example Source: https://github.com/asana/node/blob/main/test/fixtures/wpt/resource-timing/resources/sw-install.html Installs a service worker, waits for it to activate, and sets up message listeners for communication with the opener window. Handles unregistration requests from the opener. ```javascript (async () => { const script = '/resource-timing/resources/sw.js'; const scope = '/resource-timing/resources/'; const registration = await service_worker_reregister(script, scope); await wait_for_state_activated(registration.installing); const opener = window.opener; if (!opener) { return; } opener.postMessage("installed", "*"); window.addEventListener("message", async e => { if (e.data === "unregister") { await registration.unregister(); opener.postMessage("unregistered", "*"); } }); })(); ``` -------------------------------- ### Basic Benchmark Setup Source: https://github.com/asana/node/blob/main/doc/contributing/writing-and-running-benchmarks.md Sets up a benchmark with custom configurations and options. The `main` function contains the code to be benchmarked, and `bench.start()` and `bench.end()` control the timing. Code outside `main` runs twice. ```javascript 'use strict'; const common = require('../common.js'); const { SlowBuffer } = 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 const BufferConstructor = conf.type === 'fast' ? Buffer : SlowBuffer; for (let i = 0; i < conf.n; i++) { new BufferConstructor(conf.size); } // End the timer, pass in the number of operations bench.end(conf.n); } ``` -------------------------------- ### Equivalent npm init and npm exec commands Source: https://github.com/asana/node/blob/main/deps/npm/docs/output/commands/npm-init.html Demonstrates equivalent commands for npm init and npm exec, showing how options are passed through. ```bash npm init foo -y --registry= -- --hello -a # is equivalent to npm exec -y --registry= -- create-foo --hello -a ``` -------------------------------- ### Install FIPS Provider (Unix Example) Source: https://github.com/asana/node/blob/main/deps/openssl/openssl/README-FIPS.md This command installs the FIPS provider on Unix systems after OpenSSL has been configured with 'enable-fips'. It copies the shared library and runs the FIPS module self-tests. ```bash $ make install ``` ```bash $ make install_fips # for `enable-fips` only ``` -------------------------------- ### Serve Node.js Documentation Locally Source: https://github.com/asana/node/blob/main/BUILDING.md Start a local static file server to browse the documentation in a web browser. ```bash make docserve ``` -------------------------------- ### CPU Profiler Example (Promises API) Source: https://github.com/asana/node/blob/main/doc/api/inspector.md Enable and use the CPU profiler via the Promises API. This example starts profiling, allows for business logic execution, stops profiling, and saves the profile to a file. ```mjs import { Session } from 'node:inspector/promises'; import fs from 'node:fs'; const session = new Session(); session.connect(); await session.post('Profiler.enable'); await session.post('Profiler.start'); // Invoke business logic under measurement here... // some time later... const { profile } = await session.post('Profiler.stop'); // Write profile to disk, upload, etc. fs.writeFileSync('./profile.cpuprofile', JSON.stringify(profile)); ``` -------------------------------- ### Add Code Example to `http.createServer` Method Source: https://github.com/asana/node/blob/main/doc/changelogs/CHANGELOG_V14.md Demonstrates the basic usage of `http.createServer` to create an HTTP server. This example shows how to handle incoming requests and send responses. ```javascript const http = require('http'); const server = http.createServer((req, res) => { res.statusCode = 200; res.setHeader('Content-Type', 'text/plain'); res.end('Hello, World!\n'); }); server.listen(port, hostname, () => { console.log(`Server running at http://${hostname}:${port}/`); }); ``` -------------------------------- ### Example package.json with peerDependenciesMeta Source: https://github.com/asana/node/blob/main/deps/npm/docs/content/configuring-npm/package-json.md Use peerDependenciesMeta to mark peer dependencies as optional, preventing npm warnings if they are not installed. ```json { "name": "tea-latte", "version": "1.3.5", "peerDependencies": { "tea": "2.x", "soy-milk": "1.2" }, "peerDependenciesMeta": { "soy-milk": { "optional": true } } } ``` -------------------------------- ### Out-of-Tree Build Setup (Windows) Source: https://github.com/asana/node/blob/main/deps/openssl/openssl/INSTALL.md Prepare a separate directory for building OpenSSL on Windows. Navigate to the build directory and then execute the Configure script. ```batch $ C: $ mkdir \temp-openssl $ cd \temp-openssl $ perl d:\PATH\TO\OPENSSL\SOURCE\Configure [[ options ]] ``` -------------------------------- ### Basic Server Example with Busboy Source: https://github.com/asana/node/blob/main/deps/undici/src/node_modules/@fastify/busboy/README.md This example demonstrates a basic HTTP server that uses Busboy to parse incoming multipart/form-data requests. It handles both POST requests for form submissions and GET requests to display an HTML form. ```javascript var http = require('http'); var Busboy = require('busboy'); var inspect = require('util').inspect; http.createServer(function(req, res) { if (req.method === 'POST') { var busboy = new Busboy({ headers: req.headers }); busboy.on('file', function(fieldname, file, filename, encoding, mimetype) { console.log('File [' + fieldname + ']: filename: ' + filename + ', encoding: ' + encoding + ', mimetype: ' + mimetype); file.on('data', function(data) { console.log('File [' + fieldname + '] got ' + data.length + ' bytes'); }); file.on('end', function() { console.log('File [' + fieldname + '] Finished'); }); }); busboy.on('field', function(fieldname, val, fieldnameTruncated, valTruncated) { console.log('Field [' + fieldname + ']: value: ' + inspect(val)); }); busboy.on('finish', function() { console.log('Done parsing form!'); res.writeHead(303, { Connection: 'close', Location: '/' }); res.end(); }); req.pipe(busboy); } else if (req.method === 'GET') { res.writeHead(200, { Connection: 'close' }); res.end('\
\
\
\ Node.js rules!\ \
\ '); } }).listen(8000, function() { console.log('Listening for requests'); }); // Example output: // // Listening for requests // Field [textfield]: value: 'testing! :-)' // Field [selectfield]: value: '9001' // Field [checkfield]: value: 'on' // Done parsing form! ``` } ] } ] } ```US ```javascript var http = require('http'); var Busboy = require('busboy'); var inspect = require('util').inspect; http.createServer(function(req, res) { if (req.method === 'POST') { var busboy = new Busboy({ headers: req.headers }); busboy.on('file', function(fieldname, file, filename, encoding, mimetype) { console.log('File [' + fieldname + ']: filename: ' + filename + ', encoding: ' + encoding + ', mimetype: ' + mimetype); file.on('data', function(data) { console.log('File [' + fieldname + '] got ' + data.length + ' bytes'); }); file.on('end', function() { console.log('File [' + fieldname + '] Finished'); }); }); busboy.on('field', function(fieldname, val, fieldnameTruncated, valTruncated) { console.log('Field [' + fieldname + ']: value: ' + inspect(val)); }); busboy.on('finish', function() { console.log('Done parsing form!'); res.writeHead(303, { Connection: 'close', Location: '/' }); res.end(); }); req.pipe(busboy); } else if (req.method === 'GET') { res.writeHead(200, { Connection: 'close' }); res.end('\
\
\
\ Node.js rules!\ \
\ '); } }).listen(8000, function() { console.log('Listening for requests'); }); // Example output: // // Listening for requests // Field [textfield]: value: 'testing! :-)' // Field [selectfield]: value: '9001' // Field [checkfield]: value: 'on' // Done parsing form! ``` ``` -------------------------------- ### N-API 'Hello World' Example Source: https://github.com/asana/node/blob/main/doc/changelogs/CHANGELOG_V8.md A basic 'Hello World' example for N-API, demonstrating the fundamental structure for creating Node.js addons in C/C++. ```c #include NAPI_MODULE_INIT() { return exports; } ``` -------------------------------- ### Start SimpleHTTPServer Source: https://github.com/asana/node/blob/main/deps/v8/tools/heap-stats/README.md Use this command to start a simple HTTP server for hosting the Heap Stats tool. Navigate to the tool's directory first. ```shell cd tools/heap-stats python -m SimpleHTTPServer 8000 ``` -------------------------------- ### Circular Dependency Example: a.js Source: https://github.com/asana/node/blob/main/doc/api/modules.md This JavaScript file is part of a circular dependency example. It logs its starting state, exports a `done` flag, and requires './b.js'. The `done` flag is initially `false` and set to `true` after './b.js' has been loaded. ```javascript console.log('a starting'); exports.done = false; const b = require('./b.js'); console.log('in a, b.done = %j', b.done); exports.done = true; console.log('a done'); ``` -------------------------------- ### MinGW Cross-Compilation Configuration Source: https://github.com/asana/node/blob/main/deps/openssl/openssl/NOTES-WINDOWS.md Example configuration command for cross-compiling OpenSSL using MinGW-w64. Ensure necessary add-on packages are installed. ```bash ./Configure mingw64 --cross-compile-prefix=x86_64-w64-mingw32- ``` -------------------------------- ### Build with OpenMP, SSSE3, and AVX2 Source: https://github.com/asana/node/blob/main/deps/base64/base64/README.md This example demonstrates building the library with OpenMP, SSSE3, and AVX2 enabled simultaneously. It first cleans the build, then compiles with the specified flags, and finally builds the test suite. ```sh make clean && OPENMP=1 SSSE3_CFLAGS=-mssse3 AVX2_CFLAGS=-mavx2 make && OPENMP=1 make -C test ``` -------------------------------- ### Create REPLServer Instance Source: https://github.com/asana/node/blob/main/doc/api/repl.md Instantiate a REPLServer either using the repl.start() method or directly with the new keyword. Options can be passed to configure the REPL. ```js const repl = require('node:repl'); const options = { useColors: true }; const firstInstance = repl.start(options); const secondInstance = new repl.REPLServer(options); ``` -------------------------------- ### Get current npm registry configuration Source: https://github.com/asana/node/blob/main/deps/npm/docs/content/commands/npm-doctor.md Display the configured npm registry URL. This is useful for troubleshooting and understanding where packages are being installed from. ```bash npm config get registry ``` -------------------------------- ### Example package.json with peerDependencies Source: https://github.com/asana/node/blob/main/deps/npm/docs/content/configuring-npm/package-json.md Define peerDependencies to specify compatibility with a host tool or library, typically for plugins. npm v7+ installs these by default. ```json { "name": "tea-latte", "version": "1.3.5", "peerDependencies": { "tea": "2.x" } } ``` -------------------------------- ### Synopsis of npm start command Source: https://github.com/asana/node/blob/main/deps/npm/docs/content/commands/npm-start.md This is the basic syntax for the npm start command, optionally followed by additional arguments. ```bash npm start [-- ] ``` -------------------------------- ### Cross-Compile Setup Script Source: https://github.com/asana/node/blob/main/deps/cares/INSTALL.md An example shell script to set up environment variables and configure c-ares for cross-compilation for an IBM 405GP PowerPC processor. ```bash #! /bin/sh export PATH=$PATH:/opt/hardhat/devkit/ppc/405/bin export CPPFLAGS="-I/opt/hardhat/devkit/ppc/405/target/usr/include" export AR=ppc_405-ar export AS=ppc_405-as export LD=ppc_405-ld export RANLIB=ppc_405-ranlib export CC=ppc_405-gcc export NM=ppc_405-nm ./configure --target=powerpc-hardhat-linux \ --host=powerpc-hardhat-linux \ --build=i586-pc-linux-gnu \ --prefix=/opt/hardhat/devkit/ppc/405/target/usr/local \ --exec-prefix=/usr/local ``` -------------------------------- ### Example Project Structure with Workspaces Source: https://github.com/asana/node/blob/main/deps/npm/docs/output/using-npm/workspaces.html Illustrates the file structure after defining a workspace. The nested package 'packages/a' is symlinked into the root 'node_modules' after `npm install`. ```text .\n+-- package.json\n`-- packages\n +-- a\n | `-- package.json ``` ```text .\n+-- node_modules\n| `-- a -> ../packages/a\n+-- package-lock.json\n+-- package.json\n`-- packages\n +-- a\n | `-- package.json ``` -------------------------------- ### Top-level build.info Example Source: https://github.com/asana/node/blob/main/deps/openssl/openssl/Configurations/README-design.md Declares libraries to be built and specifies include directories and library dependencies for the top-level build. ```makefile # build.info LIBS=libcrypto libssl INCLUDE[libcrypto]=include INCLUDE[libssl]=include DEPEND[libssl]=libcrypto ``` -------------------------------- ### Caret Dependency Example (Below 1.0.0) Source: https://github.com/asana/node/blob/main/deps/npm/docs/output/commands/npm-update.html Illustrates how npm update handles caret dependencies for versions below 1.0.0. It installs the highest-sorting version that satisfies the range. ```json { "dependencies": { "dep1": "^0.2.0" } } ``` ```json { "dependencies": { "dep1": "^0.4.0" } } ``` -------------------------------- ### Node.js Startup Snapshot CLI Usage Source: https://github.com/asana/node/blob/main/doc/api/v8.md This example demonstrates how to use the Node.js `--snapshot-blob` and `--build-snapshot` flags to create and use startup snapshots. This is an experimental feature. ```console $ node --snapshot-blob snapshot.blob --build-snapshot entry.js ``` -------------------------------- ### Get Inspector URL Source: https://github.com/asana/node/blob/main/doc/api/inspector.md Retrieve the URL of the active inspector. Returns `undefined` if no inspector is active. Examples show usage with different CLI flags. ```console $ node --inspect -p 'inspector.url()' Debugger listening on ws://127.0.0.1:9229/166e272e-7a30-4d09-97ce-f1c012b43c34 For help, see: https://nodejs.org/en/docs/inspector ws://127.0.0.1:9229/166e272e-7a30-4d09-97ce-f1c012b43c34 $ node --inspect=localhost:3000 -p 'inspector.url()' Debugger listening on ws://localhost:3000/51cf8d0e-3c36-4c59-8efd-54519839e56a For help, see: https://nodejs.org/en/docs/inspector ws://localhost:3000/51cf8d0e-3c36-4c59-8efd-54519839e56a $ node -p 'inspector.url()' undefined ``` -------------------------------- ### Library build.info Example with Generation Rule Source: https://github.com/asana/node/blob/main/deps/openssl/openssl/Configurations/README-design.md Specifies library production, source files, object file dependencies, and a rule for generating a header file using a script. ```makefile # crypto/build.info LIBS=../libcrypto SOURCE[../libcrypto]=aes.c evp.c cversion.c DEPEND[cversion.o]=buildinf.h GENERATE[buildinf.h]=../util/mkbuildinf.pl "$(CC) $(CFLAGS)" "$(PLATFORM)" DEPEND[buildinf.h]=../Makefile DEPEND[../util/mkbuildinf.pl]=../util/Foo.pm ``` -------------------------------- ### Build and Load V8 Snapshots Source: https://github.com/asana/node/blob/main/doc/api/cli.md Use `--build-snapshot` to generate a snapshot blob and `--snapshot-blob` to load it. The first example demonstrates initializing an application and snapshotting its state, then loading it. The second shows using `v8.startupSnapshot` to set a custom deserialization function, avoiding the need for an entry script at load time. ```bash $ 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 ``` ```bash $ echo "require('v8').startupSnapshot.setDeserializeMainFunction(() => console.log('I am from the snapshot'))" > snapshot.js $ node --snapshot-blob snapshot.blob --build-snapshot snapshot.js $ node --snapshot-blob snapshot.blob I am from the snapshot ``` -------------------------------- ### Worker Process: Listen for 'online' Event Source: https://github.com/asana/node/blob/main/doc/api/cluster.md Example of forking a worker and attaching an 'online' event listener to it. This event is emitted when a worker has successfully started. ```js cluster.fork().on('online', () => { // Worker is online }); ``` -------------------------------- ### Select Dependencies by Keyword Prefix Source: https://github.com/asana/node/blob/main/deps/npm/docs/output/using-npm/dependency-selectors.html This example shows how to select dependencies where the 'keywords' array starts with 'react'. It utilizes the attribute selector syntax for arrays. ```css *:attr([keywords^=react]) ``` -------------------------------- ### Download and Build Latest OpenSSL Release (Example) Source: https://github.com/asana/node/blob/main/deps/openssl/openssl/README-FIPS.md This example shows downloading, extracting, and preparing the latest OpenSSL release (3.1.0 in this case) for building. This is the second step when using a FIPS provider with a separate latest release. ```bash $ wget https://www.openssl.org/source/openssl-3.1.0.tar.gz $ tar -xf openssl-3.1.0.tar.gz $ cd openssl-3.1.0 ``` -------------------------------- ### Basic Worker Thread Example Source: https://github.com/asana/node/blob/main/doc/api/worker_threads.md This example demonstrates how to create a Worker thread to perform a task asynchronously. It includes setup for the main thread to spawn a worker and the worker thread to perform work and communicate back. Use a pool of Workers for practical applications to manage overhead. ```javascript const { Worker, isMainThread, parentPort, workerData, } = require('node:worker_threads'); if (isMainThread) { module.exports = function parseJSAsync(script) { return new Promise((resolve, reject) => { const worker = new Worker(__filename, { workerData: script, }); worker.on('message', resolve); worker.on('error', reject); worker.on('exit', (code) => { if (code !== 0) reject(new Error(`Worker stopped with exit code ${code}`)); }); }); }; } else { const { parse } = require('some-js-parsing-library'); const script = workerData; parentPort.postMessage(parse(script)); } ``` -------------------------------- ### Basic Search Example Source: https://github.com/asana/node/blob/main/deps/npm/node_modules/libnpmsearch/README.md Demonstrates how to perform a basic search for packages using the libnpmsearch library. Requires an async context to use await. ```javascript const search = require('libnpmsearch') console.log(await search('libnpm')) => [ { name: 'libnpm', description: 'programmatic npm API', ...etc }, { name: 'libnpmsearch', description: 'Programmatic API for searching in npm and compatible registries', ...etc }, ...more ] ``` -------------------------------- ### Example Package JSON with Caret Dependency Source: https://github.com/asana/node/blob/main/deps/npm/docs/content/commands/npm-update.md Illustrates a `package.json` where 'dep1' has a caret dependency. `npm update` will install the latest version of 'dep1' that satisfies '^1.1.1'. ```json "dependencies": { "dep1": "^1.1.1" } ``` -------------------------------- ### Initialize and Load Configuration Source: https://github.com/asana/node/blob/main/deps/npm/node_modules/@npmcli/config/README.md Demonstrates how to initialize the Config class with various options and load the configuration. It also shows how to handle potential errors during loading and validate the loaded configuration. ```javascript const Config = require('@npmcli/config') const { shorthands, definitions, flatten } = require('@npmcli/config/lib/definitions') const conf = new Config({ // path to the npm module being run npmPath: resolve(__dirname, '..'), definitions, shorthands, flatten, // optional, defaults to process.argv // argv: [] <- if you are using this package in your own cli // and dont want to have colliding argv argv: process.argv, // optional, defaults to process.env env: process.env, // optional, defaults to process.execPath execPath: process.execPath, // optional, defaults to process.platform platform: process.platform, // optional, defaults to process.cwd() cwd: process.cwd(), }) // emits log events on the process object // see `proc-log` for more info process.on('log', (level, ...args) => { console.log(level, ...args) }) // returns a promise that fails if config loading fails, and // resolves when the config object is ready for action conf.load().then(() => { conf.validate() console.log('loaded ok! some-key = ' + conf.get('some-key')) }).catch(er => { console.error('error loading configs!', er) }) ``` -------------------------------- ### Get Original argv[0] (Console) Source: https://github.com/asana/node/blob/main/doc/api/process.md Retrieve a read-only copy of the original value of argv[0] passed when Node.js starts. This is useful for understanding how the process was invoked. ```console $ bash -c 'exec -a customArgv0 ./node' > process.argv[0] '/Volumes/code/external/node/out/Release/node' > process.argv0 'customArgv0' ``` -------------------------------- ### Example package.json Dependencies Source: https://github.com/asana/node/blob/main/deps/npm/docs/content/configuring-npm/package-json.md Illustrates various valid ways to specify package dependencies and version ranges in a `package.json` file. ```json { "dependencies": { "foo": "1.0.0 - 2.9999.9999", "bar": ">=1.0.2 <2.1.2", "baz": ">1.0.2 <=2.3.4", "boo": "2.0.1", "qux": "<1.0.0 || >=2.3.1 <2.4.5 || >=2.5.2 <3.0.0", "asd": "http://asdf.com/asdf.tar.gz", "til": "~1.2", "elf": "~1.2.3", "two": "2.x", "thr": "3.3.x", "lat": "latest", "dyl": "file:../dyl" } } ``` -------------------------------- ### CPU Profiler Example Source: https://github.com/asana/node/blob/main/doc/api/inspector.md Demonstrates how to use the inspector module to profile CPU usage. It enables the profiler, starts recording, and then stops it to save the profile data to a file. ```javascript const inspector = require('node:inspector'); const fs = require('node:fs'); const session = new inspector.Session(); session.connect(); session.post('Profiler.enable', () => { session.post('Profiler.start', () => { // Invoke business logic under measurement here... // some time later... session.post('Profiler.stop', (err, { profile }) => { // Write profile to disk, upload, etc. if (!err) { fs.writeFileSync('./profile.cpuprofile', JSON.stringify(profile)); } }); }); }); ``` -------------------------------- ### Initialize WASI with CommonJS Source: https://github.com/asana/node/blob/main/doc/api/wasi.md Shows how to set up the WASI environment with command-line arguments, environment variables, and preopened directories using CommonJS. ```cjs 'use strict'; const { readFile } = require('node:fs/promises'); const { WASI } = require('wasi'); const { argv, env } = require('node:process'); const { join } = require('node:path'); const wasi = new WASI({ version: 'preview1', args: argv, env, preopens: { '/local': '/some/real/path/that/wasm/can/access', }, }); (async () => { const wasm = await WebAssembly.compile( await readFile(join(__dirname, 'demo.wasm')), ); const instance = await WebAssembly.instantiate(wasm, wasi.getImportObject()); wasi.start(instance); })(); ``` -------------------------------- ### Example Package JSON with Caret Dependency Below 1.0.0 Source: https://github.com/asana/node/blob/main/deps/npm/docs/content/commands/npm-update.md Demonstrates a caret dependency on a version below 1.0.0. `npm update` will install the highest version satisfying '^0.4.0', which is '0.4.1' in this case. ```json "dependencies": { "dep1": "^0.4.0" } ``` -------------------------------- ### Example: Using Sign and Verify as Streams (CJS) Source: https://github.com/asana/node/blob/main/doc/api/crypto.md This example demonstrates how to use the `Sign` and `Verify` classes as streams in a CJS environment. ```APIDOC ## Example: Using `Sign` and `Verify` objects as streams (CJS) ```cjs const { generateKeyPairSync, createSign, createVerify, } = require('node:crypto'); const { privateKey, publicKey } = generateKeyPairSync('ec', { namedCurve: 'sect239k1', }); const sign = createSign('SHA256'); sign.write('some data to sign'); sign.end(); const signature = sign.sign(privateKey, 'hex'); const verify = createVerify('SHA256'); verify.write('some data to sign'); verify.end(); console.log(verify.verify(publicKey, signature, 'hex')); // Prints: true ``` ``` -------------------------------- ### Build Documentation (ePub) Source: https://github.com/asana/node/blob/main/deps/uv/README.md Builds the documentation in ePub format. This command is run from the root of the libuv repository. ```bash make epub ``` -------------------------------- ### Platform-Dependent Build Directory Setup Source: https://github.com/asana/node/blob/main/deps/openssl/openssl/CHANGES.md This example demonstrates how to set up a platform-dependent build directory outside the OpenSSL source tree. It uses symbolic links to reference source files. ```bash # Place yourself outside of the OpenSSL source tree. In # this example, the environment variable OPENSSL_SOURCE # is assumed to contain the absolute OpenSSL source directory. mkdir -p objtree/"`uname -s`-`uname -r`-`uname -m`" cd objtree/"`uname -s`-`uname -r`-`uname -m`" (cd $OPENSSL_SOURCE; find . -type f) | while read F; mkdir -p `dirname $F` ln -s $OPENSSL_SOURCE/$F $F done ``` -------------------------------- ### Circular Dependency Example: b.js Source: https://github.com/asana/node/blob/main/doc/api/modules.md This JavaScript file is part of a circular dependency example. It logs its starting state, exports a `done` flag, and requires './a.js'. The `done` flag is initially `false` and set to `true` after './a.js' has been loaded. Note that when './a.js' is required, it might return an unfinished copy due to the circular dependency. ```javascript console.log('b starting'); exports.done = false; const a = require('./a.js'); console.log('in b, a.done = %j', a.done); exports.done = true; console.log('b done'); ``` -------------------------------- ### Example: Using Sign and Verify as Streams (MJS) Source: https://github.com/asana/node/blob/main/doc/api/crypto.md This example demonstrates how to use the `Sign` and `Verify` classes as streams in an MJS environment. ```APIDOC ## Example: Using `Sign` and `Verify` objects as streams (MJS) ```mjs const { generateKeyPairSync, createSign, createVerify, } = await import('node:crypto'); const { privateKey, publicKey } = generateKeyPairSync('ec', { namedCurve: 'sect239k1', }); const sign = createSign('SHA256'); sign.write('some data to sign'); sign.end(); const signature = sign.sign(privateKey, 'hex'); const verify = createVerify('SHA256'); verify.write('some data to sign'); verify.end(); console.log(verify.verify(publicKey, signature, 'hex')); // Prints: true ``` ``` -------------------------------- ### Accessing nested package.json script variables Source: https://github.com/asana/node/blob/main/deps/npm/docs/content/using-npm/scripts.md Nested fields within the 'scripts' object in package.json can also be accessed as environment variables. This example shows how to access a specific install script. ```bash process.env.npm_package_scripts_install === "foo.js" ``` -------------------------------- ### Create HTTP/2 Server and Handle Streams Source: https://github.com/asana/node/blob/main/doc/api/http2.md Example of creating an HTTP/2 server and logging the path and custom headers from incoming streams. ```javascript const http2 = require('node:http2'); const server = http2.createServer(); server.on('stream', (stream, headers) => { console.log(headers[':path']); console.log(headers.ABC); }); ``` -------------------------------- ### Forwarding options to npm exec Source: https://github.com/asana/node/blob/main/deps/npm/docs/content/commands/npm-init.md This example demonstrates how options are passed to both the npm CLI and a create package. It shows equivalent commands for initializing a package with specific options. ```bash npm init foo -y --registry= -- --hello -a # equivalent to npm exec -y --registry= -- create-foo --hello -a ``` -------------------------------- ### Example Package JSON with Tilde Dependency Source: https://github.com/asana/node/blob/main/deps/npm/docs/content/commands/npm-update.md Shows a `package.json` with a tilde dependency. `npm update` will install the highest version of 'dep1' that satisfies '~1.1.1', which is typically a patch version update. ```json "dependencies": { "dep1": "~1.1.1" } ``` -------------------------------- ### Calculate Event Loop Utilization Source: https://github.com/asana/node/blob/main/doc/api/perf_hooks.md Calculate Event Loop Utilization (ELU) to measure the time the event loop has been idle and active. This example shows how to get the ELU after a blocking operation. ```javascript 'use strict'; const { eventLoopUtilization } = require('node:perf_hooks').performance; const { spawnSync } = require('node:child_process'); setImmediate(() => { const elu = eventLoopUtilization(); spawnSync('sleep', ['5']); console.log(eventLoopUtilization(elu).utilization); }); ``` -------------------------------- ### MockPool request example Source: https://github.com/asana/node/blob/main/deps/undici/src/docs/api/MockPool.md Intercepts GET requests to '/foo' and mocks a 200 response with 'foo' as the body. It then uses `mockPool.request` to make the request and logs the status code and response body. ```javascript import { MockAgent } from 'undici' const mockAgent = new MockAgent() const mockPool = mockAgent.get('http://localhost:3000') mockPool.intercept({ path: '/foo', method: 'GET', }).reply(200, 'foo') const { statusCode, body } = await mockPool.request({ origin: 'http://localhost:3000', path: '/foo', method: 'GET' }) console.log('response received', statusCode) // response received 200 for await (const data of body) { console.log('data', data.toString('utf8')) // data foo } ``` -------------------------------- ### Running a command with npx Source: https://github.com/asana/node/blob/main/deps/npm/docs/output/commands/npm-exec.html This example shows the equivalent command using `npx`. Note that all flags and options must precede positional arguments. ```bash npx foo@latest bar --package=@npmcli/foo ``` -------------------------------- ### Get and Set MIME Subtype (CommonJS) Source: https://github.com/asana/node/blob/main/doc/api/util.md Access and modify the 'subtype' portion of a MIMEType object. Changes to the subtype are reflected in the string representation of the MIME type. This example uses CommonJS syntax. ```javascript const { MIMEType } = require('node:util'); const myMIME = new MIMEType('text/ecmascript'); console.log(myMIME.subtype); // Prints: ecmascript myMIME.subtype = 'javascript'; console.log(myMIME.subtype); // Prints: javascript console.log(String(myMIME)); // Prints: text/javascript ```