### Install All Project Dependencies with npm Source: https://nodejs.org/en/learn/getting-started/an-introduction-to-the-npm-package-manager Installs all dependencies listed in the package.json file for a project. If the node_modules folder does not exist, it will be created. ```bash npm install ``` -------------------------------- ### Install Node.js Type Definitions using npm Source: https://nodejs.org/en/learn/typescript/introduction This command installs the necessary type definitions for Node.js APIs as a development dependency. These definitions enable TypeScript to understand Node.js APIs, providing type checking and autocompletion. ```bash npm add --save-dev @types/node ``` -------------------------------- ### Configure base test setup with loaders Source: https://nodejs.org/en/learn/test-runner/using-test-runner Demonstrates how to register loaders, such as TypeScript loaders, in a base setup file that is imported by other test setup modules. ```JavaScript import { register } from 'node:module'; register('some-typescript-loader'); ``` -------------------------------- ### Import and Start Node.js REPL Source: https://nodejs.org/en/learn/command-line/how-to-use-the-nodejs-repl This snippet demonstrates how to import the 'repl' module in Node.js using CommonJS syntax and start a basic REPL session. No external dependencies are required. ```javascript const repl = require('node:repl'); repl.start(); ``` -------------------------------- ### Initialize a TCP Server with net.createServer Source: https://nodejs.org/en/learn/asynchronous-work/event-loop-timers-and-nexttick Demonstrates setting up a basic TCP server using the net module. This example highlights the event-driven nature of Node.js where connection and listening events are handled asynchronously. ```javascript const server = net.createServer(); server.on('connection', conn => {}); server.listen(8080); server.on('listening', () => {}); ``` -------------------------------- ### Log output to console using Node.js Source: https://nodejs.org/en/learn/command-line/output-to-the-command-line-using-nodejs Demonstrates basic console logging, including passing multiple variables and using format specifiers like %s, %d, %i, and %o. ```javascript const x = 'x'; const y = 'y'; console.log(x, y); console.log('My %s has %d ears', 'cat', 2); console.log('%o', Number); ``` -------------------------------- ### Executing Node.js scripts and starting the REPL Source: https://nodejs.org/en/learn/command-line/how-to-use-the-nodejs-repl Commands to run a specific JavaScript file or launch the interactive REPL session directly from the terminal. ```shell node script.js node ``` -------------------------------- ### Install a Single Package with npm Source: https://nodejs.org/en/learn/getting-started/an-introduction-to-the-npm-package-manager Installs a specific package and, since npm 5, automatically adds it to the dependencies in the package.json file. Use flags like --save-dev, --no-save, or --save-optional to control how the package is saved. ```bash npm install ``` ```bash npm install --save-dev ``` ```bash npm install --no-save ``` ```bash npm install --save-optional ``` ```bash npm install --no-optional ``` -------------------------------- ### Install Specific Package Version with npm Source: https://nodejs.org/en/learn/getting-started/an-introduction-to-the-npm-package-manager Installs a package at a specific version, adhering to the semantic versioning (semver) standard. This is useful for ensuring compatibility or avoiding issues with the latest releases. ```bash npm install @ ``` -------------------------------- ### Chain Streams with Transform Source: https://nodejs.org/en/learn/modules/backpressuring-in-streams Demonstrates how to chain a Readable stream through a Transform stream into a Writable stream. This setup automatically manages backpressure, though performance can be tuned via highWaterMark settings. ```javascript Readable.pipe(Transformable).pipe(Writable); ``` -------------------------------- ### Create a Transform stream for data modification Source: https://nodejs.org/en/learn/modules/how-to-use-streams Illustrates how to instantiate a Transform stream to process input data. The example uses the transform function to convert incoming data to uppercase before pushing it to the output. ```javascript const { Transform } = require('node:stream'); const upper = new Transform({ transform(data, enc, cb) { this.push(data.toString().toUpperCase()); cb(); }, }); ``` -------------------------------- ### Start Node.js REPL with Custom Prompt Source: https://nodejs.org/en/learn/command-line/how-to-use-the-nodejs-repl This code shows how to initiate a Node.js REPL session with a custom prompt string. The 'repl.start()' function accepts an optional string argument for the prompt. The output is a REPL instance that can be further configured. ```javascript // a Unix style prompt const local = repl.start('$ '); ``` -------------------------------- ### Style terminal output Source: https://nodejs.org/en/learn/command-line/output-to-the-command-line-using-nodejs Demonstrates how to apply colors and styles to console output using the styleText function from the node:util module. ```javascript import { styleText } from 'node:util'; console.log( styleText(['red'], 'This is red text ') + styleText(['green', 'bold'], 'and this is green bold text ') + 'this is normal text' ); ``` -------------------------------- ### Node.js Readable Stream: Basic .push() Usage Source: https://nodejs.org/en/learn/modules/backpressuring-in-streams This example demonstrates how to create and use a custom Readable stream in Node.js. It shows how to push data onto the stream using `this.push()` and how to signal the end of the stream by pushing `null`. The stream is then consumed by listening for the 'data' event. ```javascript const { Readable } = require('node:stream'); // Create a custom Readable stream const myReadableStream = new Readable({ objectMode: true, read(size) { // Push some data onto the stream this.push({ message: 'Hello, world!' }); this.push(null); // Mark the end of the stream }, }); // Consume the stream myReadableStream.on('data', chunk => { console.log(chunk); }); // Output: // { message: 'Hello, world!' } ``` -------------------------------- ### Node.js Constant-Time Callback Example Source: https://nodejs.org/en/learn/asynchronous-work/dont-block-the-event-loop Demonstrates a simple Node.js Express route handler that executes in constant time. This is a good practice to ensure the Event Loop is not blocked, allowing for fair client scheduling. ```javascript app.get('/constant-time', (req, res) => { res.sendStatus(200); }); ``` -------------------------------- ### Node.js O(n) Callback Example Source: https://nodejs.org/en/learn/asynchronous-work/dont-block-the-event-loop Illustrates a Node.js Express route handler with an O(n) computational complexity. This callback's execution time scales linearly with the input 'n', which can impact Event Loop responsiveness for large values of 'n'. ```javascript app.get('/countToN', (req, res) => { const n = req.query.n; // n iterations before giving someone else a turn for (let i = 0; i < n; i++) { console.log(`Iter ${i}`); } res.sendStatus(200); }); ``` -------------------------------- ### Implement TCP communication using Duplex streams Source: https://nodejs.org/en/learn/modules/how-to-use-streams Shows the usage of Duplex streams via the 'net' module to create a TCP server and a corresponding client. These examples demonstrate bidirectional data flow where both sides can read and write to the socket. ```javascript // TCP Server const net = require('node:net'); const server = net.createServer(socket => { socket.write('Hello from server!\n'); socket.on('data', data => { console.log(`Client says: ${data.toString()}`); }); socket.on('end', () => { console.log('Client disconnected'); }); }); server.listen(8080, () => { console.log('Server listening on port 8080'); }); ``` ```javascript // TCP Client const net = require('node:net'); const client = net.createConnection({ port: 8080 }, () => { client.write('Hello from client!\n'); }); client.on('data', data => { console.log(`Server says: ${data.toString()}`); }); client.on('end', () => { console.log('Disconnected from server'); }); ``` -------------------------------- ### Readable Stream: Respecting Backpressure with .push() Source: https://nodejs.org/en/learn/modules/backpressuring-in-streams This example demonstrates the correct way to implement a Readable stream in Node.js by checking the return value of `this.push()`. This ensures that the stream respects backpressure signals from the destination stream, preventing data overload. ```javascript class MyReadable extends Readable { _read(size) { let chunk; let canPushMore = true; while (canPushMore && null !== (chunk = getNextChunk())) { canPushMore = this.push(chunk); } } } ``` -------------------------------- ### Configure dual CJS and ESM distributions Source: https://nodejs.org/en/learn/modules/publishing-a-package Configurations for supporting both ESM and CJS simultaneously. Includes examples using standard import/require keys and the node/default fallback pattern to avoid dual-package hazards. ```json { "type": "module", "exports": { ".": { "import": "./dist/esm/index.js", "require": "./dist/index.cjs" } } } ``` ```json { "type": "module", "exports": { ".": { "node": "./dist/index.cjs", "default": "./dist/esm/index.js" } } } ``` -------------------------------- ### Perform Basic POST Request with Fetch API Source: https://nodejs.org/en/learn/getting-started/fetch Shows how to send a POST request with a JSON body and custom headers using the Fetch API. This example demonstrates payload serialization and header configuration. ```JavaScript const body = { title: 'foo', body: 'bar', userId: 1, }; async function main() { const response = await fetch('https://jsonplaceholder.typicode.com/posts', { method: 'POST', headers: { 'User-Agent': 'undici-stream-example', 'Content-Type': 'application/json', }, body: JSON.stringify(body), }); const data = await response.json(); console.log(data); } main().catch(console.error); ``` -------------------------------- ### Node.js Timer Delay Example Source: https://nodejs.org/en/learn/asynchronous-work/event-loop-timers-and-nexttick Demonstrates how a long-running asynchronous operation can delay the execution of a scheduled timer callback. It uses `fs.readFile` and `setTimeout` to illustrate the concept. The output shows the actual delay experienced by the timer. ```javascript const fs = require('node:fs'); function someAsyncOperation(callback) { // Assume this takes 95ms to complete fs.readFile('/path/to/file', callback); } const timeoutScheduled = Date.now(); setTimeout(() => { const delay = Date.now() - timeoutScheduled; console.log(`${delay}ms have passed since I was scheduled`); }, 100); // do someAsyncOperation which takes 95 ms to complete someAsyncOperation(() => { const startCallback = Date.now(); // do something that will take 10ms... while (Date.now() - startCallback < 10) { // do nothing } }); ``` -------------------------------- ### Node.js O(n^2) Callback Example Source: https://nodejs.org/en/learn/asynchronous-work/dont-block-the-event-loop Presents a Node.js Express route handler with an O(n^2) computational complexity. This callback's execution time scales quadratically with the input 'n', making it significantly slower for larger 'n' and a potential cause of Event Loop blocking. ```javascript app.get('/countToN2', (req, res) => { const n = req.query.n; // n^2 iterations before giving someone else a turn for (let i = 0; i < n; i++) { for (let j = 0; j < n; j++) { console.log(`Iter ${i}.${j}`); } } res.sendStatus(200); }); ``` -------------------------------- ### Stream HTTP Responses with Undici Source: https://nodejs.org/en/learn/getting-started/fetch This example shows how to perform a GET request to the GitHub API using Undici's stream method. It utilizes a Writable stream to accumulate data chunks and processes the complete response once the stream finishes. ```javascript import { Writable } from 'node:stream'; import { stream } from 'undici'; async function fetchGitHubRepos() { const url = 'https://api.github.com/users/nodejs/repos'; await stream( url, { method: 'GET', headers: { 'User-Agent': 'undici-stream-example', Accept: 'application/json', }, }, res => { let buffer = ''; return new Writable({ write(chunk, encoding, callback) { buffer += chunk.toString(); callback(); }, final(callback) { try { const json = JSON.parse(buffer); console.log( 'Repository Names:', json.map(repo => repo.name) ); } catch (error) { console.error('Error parsing JSON:', error); } console.log('Stream processing completed.'); console.log(`Response status: ${res.statusCode}`); callback(); }, }); } ); } fetchGitHubRepos().catch(console.error); ``` -------------------------------- ### V8 Profiler Tick Output Example Source: https://nodejs.org/en/learn/getting-started/profiling An example of the raw tick data generated by the V8 profiler, representing stack samples and optimization events. ```text code-creation,LazyCompile,0,0x2d5000a337a0,396,"bp native array.js:1153:16",0x289f644df68,~ code-creation,LazyCompile,0,0x2d5000a33940,716,"hasOwnProperty native v8natives.js:198:30",0x289f64438d0,~ code-creation,LazyCompile,0,0x2d5000a33c20,284,"ToName native runtime.js:549:16",0x289f643bb28,~ code-creation,Stub,2,0x2d5000a33d40,182,"DoubleToIStub" code-creation,Stub,2,0x2d5000a33e00,507,"NumberToStringStub" ``` -------------------------------- ### Create a directory in Node.js Source: https://nodejs.org/en/learn/manipulating-files/working-with-folders-in-nodejs Demonstrates how to check for a folder's existence and create it synchronously using the 'fs' module. ```javascript const fs = require('node:fs'); const folderName = '/Users/joe/test'; try { if (!fs.existsSync(folderName)) { fs.mkdirSync(folderName); } } catch (err) { console.error(err); } ``` -------------------------------- ### Install ts-node for Running TypeScript Source: https://nodejs.org/en/learn/typescript/run Installs the `ts-node` package as a development dependency. This package enables running TypeScript files directly in Node.js without prior compilation. ```bash npm i -D ts-node ``` -------------------------------- ### Create a Basic Node.js HTTP Server (CJS) Source: https://nodejs.org/en/learn/getting-started/introduction-to-nodejs This CommonJS snippet demonstrates how to create a basic HTTP server using Node.js's built-in 'http' module. It listens on a specified port and hostname, responding to requests with 'Hello World'. To run, save as 'server.js' and execute with 'node server.js'. ```javascript const { createServer } = require('node:http'); const hostname = '127.0.0.1'; const port = 3000; const server = createServer((req, res) => { res.statusCode = 200; res.setHeader('Content-Type', 'text/plain'); res.end('Hello World'); }); server.listen(port, hostname, () => { console.log(`Server running at http://${hostname}:${port}/`); }); ``` -------------------------------- ### Install tsx for Running TypeScript Source: https://nodejs.org/en/learn/typescript/run Installs the `tsx` package as a development dependency. `tsx` is a TypeScript execution environment for Node.js that allows direct execution without compilation, but does not perform type checking. ```bash npm i -D tsx ``` -------------------------------- ### File Compression with Streams Source: https://nodejs.org/en/learn/modules/backpressuring-in-streams Shows how to compress a large file using zlib streams and the .pipe() method to efficiently transfer data from a read stream to a write stream. ```javascript const fs = require('node:fs'); const gzip = require('node:zlib').createGzip(); const inp = fs.createReadStream('The.Matrix.1080p.mkv'); const out = fs.createWriteStream('The.Matrix.1080p.mkv.gz'); inp.pipe(gzip).pipe(out); ``` -------------------------------- ### Perform Basic GET Request with Fetch API Source: https://nodejs.org/en/learn/getting-started/fetch Demonstrates a standard GET request using the global fetch API powered by Undici. It retrieves JSON data from a public API endpoint and logs the result to the console. ```JavaScript async function main() { const response = await fetch('https://jsonplaceholder.typicode.com/posts'); const data = await response.json(); console.log(data); } main().catch(console.error); ``` -------------------------------- ### Implementing Writable._write with proper callback handling Source: https://nodejs.org/en/learn/modules/backpressuring-in-streams Demonstrates the correct implementation of the _write method in a custom Writable stream. It ensures that callbacks are returned immediately after execution to prevent multiple callback invocations. ```javascript class MyWritable extends Writable { _write(chunk, encoding, callback) { if (chunk.toString().indexOf('a') >= 0) { return callback(); } if (chunk.toString().indexOf('b') >= 0) { return callback(); } callback(); } } ``` -------------------------------- ### TypeScript Type Error Example Source: https://nodejs.org/en/learn/typescript/transpile This snippet illustrates how TypeScript catches type errors during compilation. It shows an example where an incorrect type is assigned to a variable, and a function call with the wrong number of arguments, preventing the code from running until fixed. ```typescript type User = { name: string; age: number; }; function isAdult(user: User): boolean { return user.age >= 18; } const justine: User = { name: 'Justine', age: 'Secret!', Type 'string' is not assignable to type 'number'. }; const isJustineAnAdult: string = isAdult(justine, "I shouldn't be here!"); Expected 1 arguments, but got 2. Type 'boolean' is not assignable to type 'string'. ``` -------------------------------- ### Executing JavaScript expressions in the REPL Source: https://nodejs.org/en/learn/command-line/how-to-use-the-nodejs-repl Examples of running standard JavaScript statements and expressions within the interactive REPL environment. ```javascript console.log('test') 5 === '5' ``` -------------------------------- ### Measure execution time Source: https://nodejs.org/en/learn/command-line/output-to-the-command-line-using-nodejs Utilizes console.time() and console.timeEnd() to calculate and print the duration of a specific operation or function execution. ```javascript const doSomething = () => console.log('test'); const measureDoingSomething = () => { console.time('doSomething()'); doSomething(); console.timeEnd('doSomething()'); }; measureDoingSomething(); ``` -------------------------------- ### Optimizing stream writes with .cork() and process.nextTick() Source: https://nodejs.org/en/learn/modules/backpressuring-in-streams Shows how to batch multiple write operations using .cork() and defer the .uncork() call using process.nextTick() to ensure efficient buffer flushing at the C++ layer. ```javascript function doUncork(stream) { stream.uncork(); } ws.cork(); ws.write('hello '); ws.write('world '); process.nextTick(doUncork, ws); ws.cork(); ws.write('from '); ws.write('Matteo'); process.nextTick(doUncork, ws); ``` -------------------------------- ### Trace function execution stack Source: https://nodejs.org/en/learn/command-line/output-to-the-command-line-using-nodejs Uses console.trace() to output the current call stack, which is useful for debugging the execution flow of nested functions. ```javascript const function2 = () => console.trace(); const function1 = () => function2(); function1(); ``` -------------------------------- ### Calculating Averages with Partitioning Source: https://nodejs.org/en/learn/asynchronous-work/dont-block-the-event-loop This snippet compares an un-partitioned O(n) loop that blocks the Event Loop against a partitioned approach using setImmediate. The partitioned approach breaks the task into smaller asynchronous steps to maintain responsiveness. ```javascript // Un-partitioned average, costs O(n) for (let i = 0; i < n; i++) { sum += i; } const avg = sum / n; console.log('avg: ' + avg); ``` ```javascript // Partitioned average, each of the n asynchronous steps costs O(1). function asyncAvg(n, avgCB) { let sum = 0; function help(i, cb) { sum += i; if (i == n) { cb(sum); return; } // Schedule next operation asynchronously. setImmediate(help.bind(null, i + 1, cb)); } help(1, function (sum) { const avg = sum / n; avgCB(avg); }); } asyncAvg(n, function (avg) { console.log('avg of 1-n: ' + avg); }); ``` -------------------------------- ### Update Packages with npm Source: https://nodejs.org/en/learn/getting-started/an-introduction-to-the-npm-package-manager Checks for and installs newer versions of packages that satisfy the versioning constraints defined in package.json. You can update all packages or specify a single package. ```bash npm update ``` ```bash npm update ``` -------------------------------- ### Instantiate and Execute WebAssembly Module Source: https://nodejs.org/en/learn/getting-started/nodejs-with-webassembly This snippet shows how to read a .wasm binary file from the file system and instantiate it using the WebAssembly.instantiate method. It demonstrates accessing exported functions from the module instance to perform calculations. ```javascript const fs = require('node:fs'); // Use the readFileSync function to read the contents of the "add.wasm" file const wasmBuffer = fs.readFileSync('/path/to/add.wasm'); // Use the WebAssembly.instantiate method to instantiate the WebAssembly module WebAssembly.instantiate(wasmBuffer).then(wasmModule => { // Exported function lives under instance.exports object const { add } = wasmModule.instance.exports; const sum = add(5, 6); console.log(sum); // Outputs: 11 }); ``` -------------------------------- ### Manage WebSocket Connection and Events in Node.js Source: https://nodejs.org/en/learn/getting-started/websocket Demonstrates how to initialize a WebSocket connection, send messages upon opening, and handle incoming messages, closure events, and errors using the native WebSocket API. ```javascript // Creates a new WebSocket connection to the specified URL. const socket = new WebSocket('ws://localhost:8080'); // Executes when the connection is successfully established. socket.addEventListener('open', event => { console.log('WebSocket connection established!'); // Sends a message to the WebSocket server. socket.send('Hello Server!'); }); // Listen for messages and executes when a message is received from the server. socket.addEventListener('message', event => { console.log('Message from server: ', event.data); }); // Executes when the connection is closed, providing the close code and reason. socket.addEventListener('close', event => { console.log('WebSocket connection closed:', event.code, event.reason); }); // Executes if an error occurs during the WebSocket communication. socket.addEventListener('error', error => { console.error('WebSocket error:', error); }); ``` -------------------------------- ### Synchronous JavaScript Execution Example Source: https://nodejs.org/en/learn/asynchronous-work/javascript-asynchronous-programming-and-callbacks Demonstrates the sequential execution of JavaScript code. Variables are declared, a calculation is performed, the result is logged, and then a function is called, all in order. ```javascript const a = 1; const b = 2; const c = a * b; console.log(c); doSomething(); ``` -------------------------------- ### Create a Basic Node.js HTTP Server (ESM) Source: https://nodejs.org/en/learn/getting-started/introduction-to-nodejs This ECMAScript Module (ESM) snippet shows how to create a basic HTTP server in Node.js using the 'http' module. It functions similarly to the CJS version, responding with 'Hello World'. Save as 'server.mjs' and run with 'node server.mjs'. ```javascript import { createServer } from 'node:http'; const hostname = '127.0.0.1'; const port = 3000; const server = createServer((req, res) => { res.statusCode = 200; res.setHeader('Content-Type', 'text/plain'); res.end('Hello World'); }); server.listen(port, hostname, () => { console.log(`Server running at http://${hostname}:${port}/`); }); ``` -------------------------------- ### Validate TypeScript type safety Source: https://nodejs.org/en/learn/typescript/publishing-a-ts-package An example of a TypeScript type error where a string is incorrectly assigned to a number, demonstrating how the compiler acts as a verification tool similar to unit tests. ```typescript const foo = 'a'; const bar: number = 1 + foo; // Type 'string' is not assignable to type 'number'. ``` -------------------------------- ### Demonstrating Callback Hell in JavaScript Source: https://nodejs.org/en/learn/asynchronous-work/asynchronous-flow-control An example of deeply nested asynchronous function calls, commonly referred to as 'callback hell', which makes code difficult to read and maintain. ```javascript async1(function (input, result1) { async2(function (result2) { async3(function (result3) { async4(function (result4) { async5(function (output) { // do something with output }); }); }); }); }); ``` -------------------------------- ### Implement Async/Await for Sequential Tasks Source: https://nodejs.org/en/learn/asynchronous-work/discover-promises-in-nodejs Demonstrates how to use async/await to handle sequential asynchronous tasks in a readable, synchronous-like style compared to traditional Promise chaining. ```javascript async function performTasks() { try { const result1 = await promise1; console.log(result1); // 'First task completed' const result2 = await promise2; console.log(result2); // 'Second task completed' } catch (error) { console.error(error); // Catches any rejection or error } } performTasks(); ``` ```javascript promise1 .then(function (result1) { console.log(result1); return promise2; }) .then(function (result2) { console.log(result2); }) .catch(function (error) { console.log(error); }); ``` -------------------------------- ### Count and reset console occurrences Source: https://nodejs.org/en/learn/command-line/output-to-the-command-line-using-nodejs Shows how to track the number of times a specific string or label is printed to the console using console.count() and how to reset those counters with console.countReset(). ```javascript const oranges = ['orange', 'orange']; const apples = ['just one apple']; oranges.forEach(fruit => { console.count(fruit); }); console.countReset('orange'); oranges.forEach(fruit => { console.count(fruit); }); ``` -------------------------------- ### Execute Node.js REPL Script from Command Line Source: https://nodejs.org/en/learn/command-line/how-to-use-the-nodejs-repl This command demonstrates how to run a Node.js JavaScript file that contains REPL logic from the terminal. Ensure the file is saved (e.g., as 'repl.js') before executing this command in the same directory. ```bash node repl.js ``` -------------------------------- ### Deferred Event Handling with nextTick Source: https://nodejs.org/en/learn/asynchronous-work/event-loop-timers-and-nexttick Shows how to use nextTick to ensure event handlers are registered before an event is emitted, preventing race conditions during server initialization. ```javascript const server = net.createServer(() => {}).listen(8080); server.on('listening', () => {}); ``` -------------------------------- ### Configure GitHub Actions for npm Publishing Source: https://nodejs.org/en/learn/typescript/publishing-a-ts-package A workflow template for publishing Node.js packages to the npm registry. It includes steps for checking out code, setting up the environment, and installing dependencies, intended to be extended with the publish command. ```yaml name: Publish to npm on: push: tags: - '**@*' jobs: build: runs-on: ubuntu-latest permissions: contents: read steps: - uses: actions/checkout@v4 - uses: actions/setup-node@v4 with: node-version-file: '.nvmrc' registry-url: 'https://registry.npmjs.org' - run: npm ci ```