### Output from starting the server Source: https://nodejs.org/docs/v8.5.0/api/all.html Shows the output of the async_hooks example when only starting the server, illustrating the sequence of init, before, after, and destroy calls. ```text TCPWRAP(2): trigger: 1 execution: 1 TickObject(3): trigger: 2 execution: 1 before: 3 Timeout(4): trigger: 3 execution: 3 TIMERWRAP(5): trigger: 3 execution: 3 after: 3 destroy: 3 before: 5 before: 4 TTYWRAP(6): trigger: 4 execution: 4 SIGNALWRAP(7): trigger: 4 execution: 4 TTYWRAP(8): trigger: 4 execution: 4 >>> 4 TickObject(9): trigger: 4 execution: 4 after: 4 after: 5 before: 9 after: 9 destroy: 4 destroy: 9 destroy: 5 ``` -------------------------------- ### Starting the Node.js REPL and executing JavaScript Source: https://nodejs.org/docs/v8.5.0/api/all.html Shows how to start the Node.js REPL by running 'node' without arguments. The example demonstrates defining an array, inspecting it, and using forEach to print its elements. The REPL prints 'undefined' after each expression and uses '...' for continuation lines. ```bash $ node > const a = [1, 2, 3]; undefined > a [ 1, 2, 3 ] > a.forEach((v) => { ... console.log(v); ... }); 1 2 3 ``` -------------------------------- ### process.cpuUsage() example Source: https://nodejs.org/docs/v8.5.0/api/all.html Shows how to get CPU usage and compute a diff by passing a previous result. The example spins the CPU for 500 milliseconds and then logs the diff. ```javascript const startUsage = process.cpuUsage(); // { user: 38579, system: 6986 } // spin the CPU for 500 milliseconds const now = Date.now(); while (Date.now() - now < 500); console.log(process.cpuUsage(startUsage)); // { user: 514883, system: 11226 } ``` -------------------------------- ### path.format() POSIX examples Source: https://nodejs.org/docs/v8.5.0/api/all.html Shows three POSIX examples: with dir/root/base, with root/base, and with root/name/ext. Demonstrates property priority rules. ```javascript // If `dir`, `root` and `base` are provided, // `${dir}${path.sep}${base}` // will be returned. `root` is ignored. path.format({ root: '/ignored', dir: '/home/user/dir', base: 'file.txt' }); // Returns: '/home/user/dir/file.txt' // `root` will be used if `dir` is not specified. // If only `root` is provided or `dir` is equal to `root` then the // platform separator will not be included. `ext` will be ignored. path.format({ root: '/', base: 'file.txt', ext: 'ignored' }); // Returns: '/file.txt' // `name` + `ext` will be used if `base` is not specified. path.format({ root: '/', name: 'file', ext: '.txt' }); // Returns: '/file.txt' ``` -------------------------------- ### Start a REPL with a custom prompt using repl.start() Source: https://nodejs.org/docs/v8.5.0/api/all.html Creates and starts a REPLServer instance with a Unix-style prompt '$ '. The options parameter can be a string to specify the prompt. ```javascript const repl = require('repl'); // a Unix style prompt repl.start('$ '); ``` -------------------------------- ### process.execPath example output Source: https://nodejs.org/docs/v8.5.0/api/all.html Shows the absolute pathname of the executable that started the Node.js process, as returned by process.execPath. ```javascript '/usr/local/bin/node' ``` -------------------------------- ### Example output of process.versions Source: https://nodejs.org/docs/v8.5.0/api/all.html Shows an example object that process.versions might generate. ```javascript { http_parser: '2.3.0', node: '1.1.1', v8: '4.1.0.14', uv: '1.3.0', zlib: '1.2.8', ares: '1.10.0-DEV', modules: '43', icu: '55.1', openssl: '1.0.1k', unicode: '8.0', cldr: '29.0', tz: '2016b' } ``` -------------------------------- ### async_hooks example: track init, before, after, destroy Source: https://nodejs.org/docs/v8.5.0/api/all.html Creates an async hook that logs init, before, after, and destroy events with indentation to show calling context. Starts a net server and logs the executionAsyncId after a 10ms timeout. ```javascript let indent = 0; async_hooks.createHook({ init(asyncId, type, triggerAsyncId) { const eid = async_hooks.executionAsyncId(); const indentStr = ' '.repeat(indent); fs.writeSync( 1, `${indentStr}${type}(${asyncId}):` + ` trigger: ${triggerAsyncId} execution: ${eid}\n`); }, before(asyncId) { const indentStr = ' '.repeat(indent); fs.writeSync(1, `${indentStr}before: ${asyncId}\n`); indent += 2; }, after(asyncId) { indent -= 2; const indentStr = ' '.repeat(indent); fs.writeSync(1, `${indentStr}after: ${asyncId}\n`); }, destroy(asyncId) { const indentStr = ' '.repeat(indent); fs.writeSync(1, `${indentStr}destroy: ${asyncId}\n`); }, }).enable(); require('net').createServer(() => {}).listen(8080, () => { // Let's wait 10ms before logging the server started. setTimeout(() => { console.log('>>>', async_hooks.executionAsyncId()); }, 10); }); ``` -------------------------------- ### Run the server with node example.js Source: https://nodejs.org/docs/v8.5.0/api/all.html Command to run the example server and its expected output. ```bash $ node example.js Server running at http://127.0.0.1:3000/ ``` -------------------------------- ### repl.start([options]) Source: https://nodejs.org/docs/v8.5.0/api/all.html Starts a new REPL server with the given options. ```APIDOC ## repl.start([options]) ### Description Starts a new REPL server. The `options` object can include `prompt`, `input`, `output`, `terminal`, `eval`, `useColors`, `useGlobal`, `ignoreUndefined`, `writer`, `completer`, `replMode`, `breakEvalOnSigint`, and other properties. ### Method - (static method) ### Syntax `repl.start([options])` ### Parameters - `options` (object) - Optional - Configuration options. - `prompt` (string) - Optional - The prompt string to display. - `input` (stream.Readable) - Optional - The readable stream to listen to. - `output` (stream.Writable) - Optional - The writable stream to write output to. - `terminal` (boolean) - Optional - If `true`, specifies that the input and output streams should be treated like a TTY. - `eval` (function) - Optional - A custom evaluation function. - `useColors` (boolean) - Optional - If `true`, enables color output. - `useGlobal` (boolean) - Optional - If `true`, uses the global object instead of a local context. - `ignoreUndefined` (boolean) - Optional - If `true`, does not output the result of undefined expressions. - `writer` (function) - Optional - A function that formats the output. - `completer` (function) - Optional - A function used for tab autocompletion. - `replMode` (symbol) - Optional - The REPL mode (e.g., `repl.REPL_MODE_SLOPPY` or `repl.REPL_MODE_STRICT`). - `breakEvalOnSigint` (boolean) - Optional - If `true`, stops evaluating the current expression when `SIGINT` is received. ### Returns - `repl.REPLServer` - The created REPL server instance. ### Example ```js const repl = require('repl'); repl.start({ prompt: '> ' }); ``` ``` -------------------------------- ### request.method Source: https://nodejs.org/docs/v8.5.0/api/all.html The request method as a string. Read only. Example: 'GET', 'DELETE'. ```APIDOC ## request.method ### Description The request method as a string. Read only. Example: `'GET'`, `'DELETE'`. ### Type - ``` -------------------------------- ### Workaround: call socket.resume() to start data flow Source: https://nodejs.org/docs/v8.5.0/api/all.html The workaround for the broken example: calling socket.resume() starts the flow of data, discarding it, so the 'end' event can fire. ```javascript // Workaround net.createServer((socket) => { socket.on('end', () => { socket.end('The message was received but was not processed.\n'); }); // start the flow of data, discarding it. socket.resume(); }).listen(1337); ``` -------------------------------- ### console.timeEnd example Source: https://nodejs.org/docs/v8.5.0/api/all.html Stops a timer started with console.time and prints the elapsed time to stdout. The example shows timing a loop of 100 iterations and the output format. ```javascript console.time('100-elements'); for (let i = 0; i < 100; i++) {} console.timeEnd('100-elements'); // prints 100-elements: 225.438ms ``` -------------------------------- ### N-API approximation of JavaScript example Source: https://nodejs.org/docs/v8.5.0/api/all.html C code approximating the JavaScript example using napi_new_instance, including getting the global object, retrieving the constructor, creating a string, and calling the constructor. ```c // Get the constructor function MyObject napi_value global, constructor, arg, value; napi_status status = napi_get_global(env, &global); if (status != napi_ok) return; status = napi_get_named_property(env, global, "MyObject", &constructor); if (status != napi_ok) return; // const arg = "hello" status = napi_create_string_utf8(env, "hello", -1, &arg); if (status != napi_ok) return; napi_value* argv = &arg; size_t argc = 1; // const value = new MyObject(arg) status = napi_new_instance(env, constructor, argc, argv, &value); ``` -------------------------------- ### Create HTTPS server with pfx and passphrase Source: https://nodejs.org/docs/v8.5.0/api/all.html Alternative example for https.createServer() using pfx and passphrase options. The server responds with 'hello world'. ```javascript const https = require('https'); const fs = require('fs'); const options = { pfx: fs.readFileSync('test/fixtures/test_cert.pfx'), passphrase: 'sample' }; https.createServer(options, (req, res) => { res.writeHead(200); res.end('hello world\n'); }).listen(8000); ``` -------------------------------- ### dns.lookup() example usage Source: https://nodejs.org/docs/v8.5.0/api/all.html Resolves 'example.com' with options for family 6 and hints. Shows output with a single address, then with options.all set to true, returning an array of addresses. ```javascript const dns = require('dns'); const options = { family: 6, hints: dns.ADDRCONFIG | dns.V4MAPPED, }; dns.lookup('example.com', options, (err, address, family) => console.log('address: %j family: IPv%s', address, family)); // address: "2606:2800:220:1:248:1893:25c8:1946" family: IPv6 // When options.all is true, the result will be an Array. options.all = true; dns.lookup('example.com', options, (err, addresses) => console.log('addresses: %j', addresses)); // addresses: [{"address":"2606:2800:220:1:248:1893:25c8:1946","family":6}] ``` -------------------------------- ### buf.toString() examples Source: https://nodejs.org/docs/v8.5.0/api/all.html Decodes a Buffer to a string with optional encoding, start, and end parameters. The examples show ASCII decoding with range, hex encoding, and UTF-8 decoding with undefined encoding. ```javascript const buf1 = Buffer.allocUnsafe(26); for (let i = 0; i < 26; i++) { // 97 is the decimal ASCII value for 'a' buf1[i] = i + 97; } // Prints: abcdefghijklmnopqrstuvwxyz console.log(buf1.toString('ascii')); // Prints: abcde console.log(buf1.toString('ascii', 0, 5)); const buf2 = Buffer.from('tést'); // Prints: 74c3a97374 console.log(buf2.toString('hex')); // Prints: té console.log(buf2.toString('utf8', 0, 3)); // Prints: té console.log(buf2.toString(undefined, 0, 3)); ``` -------------------------------- ### Read last 10 bytes of a file with fs.createReadStream Source: https://nodejs.org/docs/v8.5.0/api/all.html Example that reads the last 10 bytes of a 100-byte file by setting start to 90 and end to 99. Both start and end are inclusive and zero-based. ```javascript fs.createReadStream('sample.txt', { start: 90, end: 99 }); ``` -------------------------------- ### Create HTTPS server with key and cert Source: https://nodejs.org/docs/v8.5.0/api/all.html Example for https.createServer() using key and cert options. Run with curl -k https://localhost:8000/ to test. The server responds with 'hello world'. ```javascript // curl -k https://localhost:8000/ const https = require('https'); const fs = require('fs'); const options = { key: fs.readFileSync('test/fixtures/keys/agent2-key.pem'), cert: fs.readFileSync('test/fixtures/keys/agent2-cert.pem') }; https.createServer(options, (req, res) => { res.writeHead(200); res.end('hello world\n'); }).listen(8000); ``` -------------------------------- ### Node.js HTTP server example Source: https://nodejs.org/docs/v8.5.0/api/all.html A simple web server that responds with 'Hello World'. Save as example.js and run with node example.js. ```javascript const http = require('http'); const hostname = '127.0.0.1'; const port = 3000; const server = http.createServer((req, res) => { res.statusCode = 200; res.setHeader('Content-Type', 'text/plain'); res.end('Hello World\n'); }); server.listen(port, hostname, () => { console.log(`Server running at http://${hostname}:${port}/`); }); ``` -------------------------------- ### request.url value for the example request Source: https://nodejs.org/docs/v8.5.0/api/all.html The value of request.url for the GET request shown above. It contains only the path and query string. ```text '/status?name=ryan' ``` -------------------------------- ### addon.cc - Addon entry point Source: https://nodejs.org/docs/v8.5.0/api/all.html Initializes the addon by calling MyObject::Init on the exports object. Uses NODE_MODULE macro with NODE_GYP_MODULE_NAME. ```cpp // addon.cc #include #include "myobject.h" namespace demo { using v8::Local; using v8::Object; void InitAll(Local exports) { MyObject::Init(exports); } NODE_MODULE(NODE_GYP_MODULE_NAME, InitAll) } // namespace demo ``` -------------------------------- ### options.detached - Long-Running Process Source: https://nodejs.org/docs/v8.5.0/api/all.html Example of using the detached option to start a long-running process that continues after the parent exits. ```APIDOC ## options.detached - Long-Running Process ### Description When `options.detached` is set to `true`, the child process is made the leader of a new process group and session. This example shows how to detach a child process and ignore the parent's stdio to allow it to run in the background. ### Method spawn ### Syntax `spawn(command[, args][, options])` ### Parameters - **command** (string) - Required - The command to run. - **args** (string[]) - Optional - List of string arguments. - **options** (Object) - Optional - Options for the child process. - **detached** (boolean) - Optional - If true, the child process will be made the leader of a new process group and session. - **stdio** (string|Array) - Optional - Configures the pipes between parent and child. Use `'ignore'` to detach from parent's stdio. ### Example ```javascript const { spawn } = require('child_process'); const subprocess = spawn(process.argv[0], ['child_program.js'], { detached: true, stdio: 'ignore' }); subprocess.unref(); ``` ``` -------------------------------- ### binding.gyp file for addon examples Source: https://nodejs.org/docs/v8.5.0/api/all.html Configuration file for building the addon with node-gyp. Lists the source file addon.cc. ```json { "targets": [ { "target_name": "addon", "sources": [ "addon.cc" ] } ] } ``` -------------------------------- ### Buffer.byteLength example: calculating byte length of a string Source: https://nodejs.org/docs/v8.5.0/api/all.html Demonstrates using Buffer.byteLength to get the byte length of a string, which differs from character count. The example prints the character count and byte length for a string with special characters. ```javascript const str = '\u00bd + \u00bc = \u00be'; // Prints: ½ + ¼ = ¾: 9 characters, 12 bytes console.log(`${str}: ${str.length} characters, ` + `${Buffer.byteLength(str, 'utf8')} bytes`); ``` -------------------------------- ### domain.run(fn[, ...args]) example: basic domain usage Source: https://nodejs.org/docs/v8.5.0/api/all.html Demonstrates the most basic way to use a domain: create a domain, attach an 'error' handler, and run a function inside the domain. The example simulates async operations with process.nextTick and setTimeout, and throws an error from fs.open on a non-existent file. The d.on('error') handler is triggered instead of crashing the program. ```javascript const domain = require('domain'); const fs = require('fs'); const d = domain.create(); d.on('error', (er) => { console.error('Caught error!', er); }); d.run(() => { process.nextTick(() => { setTimeout(() => { // simulating some various async stuff fs.open('non-existent file', 'r', (er, fd) => { if (er) throw er; // proceed... }); }, 100); }); }); ``` -------------------------------- ### path.basename() examples Source: https://nodejs.org/docs/v8.5.0/api/all.html Shows how to use path.basename() to get the last portion of a path, with and without an optional file extension. Passing a non-string path or ext throws a TypeError. ```javascript path.basename('/foo/bar/baz/asdf/quux.html'); // Returns: 'quux.html' path.basename('/foo/bar/baz/asdf/quux.html', '.html'); // Returns: 'quux' ``` -------------------------------- ### Write file with fs.open() (RECOMMENDED) Source: https://nodejs.org/docs/v8.5.0/api/all.html Recommended approach for writing a file: directly open with 'wx' flag and handle the 'EEXIST' error if the file already exists. Avoids race conditions. ```javascript fs.open('myfile', 'wx', (err, fd) => { if (err) { if (err.code === 'EEXIST') { console.error('myfile already exists'); return; } throw err; } writeMyData(fd); }); ``` -------------------------------- ### Demonstrate init callback with resources closed before use Source: https://nodejs.org/docs/v8.5.0/api/all.html Shows two ways to trigger the init callback for resources that are opened and closed without being used. The first creates a server and closes it in the listen callback; the second clears a timeout immediately after setting it. ```javascript require('net').createServer().listen(function() { this.close(); }); // OR clearTimeout(setTimeout(() => {}, 10)); ``` -------------------------------- ### https.get() example Source: https://nodejs.org/docs/v8.5.0/api/all.html Makes an HTTPS GET request to 'https://encrypted.google.com/' and logs the status code and headers. The response data is written to stdout, and errors are logged to stderr. ```javascript const https = require('https'); https.get('https://encrypted.google.com/', (res) => { console.log('statusCode:', res.statusCode); console.log('headers:', res.headers); res.on('data', (d) => { process.stdout.write(d); }); }).on('error', (e) => { console.error(e); }); ``` -------------------------------- ### server.listen(path[, backlog][, callback]) Source: https://nodejs.org/docs/v8.5.0/api/all.html Starts an IPC server listening on the given path. ```APIDOC ## server.listen(path[, backlog][, callback]) ### Description Starts an IPC server listening for connections on the given path. ### Method listen ### Signature server.listen(path[, backlog][, callback]) ### Parameters - **path** (String) - Required - Path the server should listen to. See Identifying paths for IPC connections. - **backlog** (number) - Optional - Common parameter of server.listen() functions. - **callback** (Function) - Optional - Common parameter of server.listen() functions. ### Returns - ### Behavior - Starts an IPC server listening on the given path. ``` -------------------------------- ### path.extname() examples Source: https://nodejs.org/docs/v8.5.0/api/all.html Returns the extension of a path from the last period to the end of the string. Returns empty string if no period or if basename starts with a period. Throws TypeError if path is not a string. ```javascript path.extname('index.html'); // Returns: '.html' path.extname('index.coffee.md'); // Returns: '.md' path.extname('index.'); // Returns: '.' path.extname('index'); // Returns: '' path.extname('.index'); // Returns: '' ``` -------------------------------- ### spawn with stdio option example Source: https://nodejs.org/docs/v8.5.0/api/all.html Example showing how to use the stdio option with child_process.spawn. It demonstrates inheriting parent's stdio, sharing only stderr, and opening an extra fd=4. ```javascript const { spawn } = require('child_process'); // Child will use parent's stdios spawn('prg', [], { stdio: 'inherit' }); // Spawn child sharing only stderr spawn('prg', [], { stdio: ['pipe', 'pipe', process.stderr] }); // Open an extra fd=4, to interact with programs presenting a // startd-style interface. spawn('prg', [], { stdio: ['pipe', null, null, null, 'pipe'] }); ``` -------------------------------- ### Using NODE_DEBUG to trace fs errors Source: https://nodejs.org/docs/v8.5.0/api/all.html Shows how to set the NODE_DEBUG environment variable to get a trace to the original call site when an error occurs. The example includes the script and the resulting error output. ```bash $ cat script.js function bad() { require('fs').readFile('/'); } bad(); $ env NODE_DEBUG=fs node script.js fs.js:88 throw backtrace; ^ Error: EISDIR: illegal operation on a directory, read ``` -------------------------------- ### process.chdir() example: change working directory Source: https://nodejs.org/docs/v8.5.0/api/all.html Demonstrates using process.chdir() to change the current working directory, with error handling for failures. Logs the starting and new directory, and catches errors if the directory does not exist. ```javascript console.log(`Starting directory: ${process.cwd()}`); try { process.chdir('/tmp'); console.log(`New directory: ${process.cwd()}`); } catch (err) { console.error(`chdir: ${err}`); } ``` -------------------------------- ### IPC connection example using net.createConnection({ path: '/tmp/echo.sock' }) Source: https://nodejs.org/docs/v8.5.0/api/all.html Shows how to connect to a Unix socket for IPC by changing the second line of the TCP example to use the path option. ```javascript const client = net.createConnection({ path: '/tmp/echo.sock' }); ``` -------------------------------- ### Example stack trace output Source: https://nodejs.org/docs/v8.5.0/api/all.html Shows the format of a stack trace: first line is ': ', followed by frames starting with 'at '. Each frame describes a call site. ```text Error: Things keep happening! at /home/gbusey/file.js:525:2 at Frobnicator.refrobulate (/home/gbusey/business-logic.js:424:21) at Actor. (/home/gbusey/actors.js:400:8) at increaseSynergy (/home/gbusey/actors.js:701:6) ``` -------------------------------- ### Example package.json for folder module Source: https://nodejs.org/docs/v8.5.0/api/all.html Shows a package.json file that specifies the main module for a folder. If placed in ./some-library, require('./some-library') loads ./some-library/lib/some-library.js. ```json { "name" : "some-library", "main" : "./lib/some-library.js" } ``` -------------------------------- ### binding.gyp - Build configuration Source: https://nodejs.org/docs/v8.5.0/api/all.html Specifies the source files for the addon target. Must include myobject.cc to build the example. ```json { "targets": [ { "target_name": "addon", "sources": [ "addon.cc", "myobject.cc" ] } ] } ``` -------------------------------- ### Handle SIGINT signal with process.on Source: https://nodejs.org/docs/v8.5.0/api/all.html Example of listening for the SIGINT signal. It resumes stdin to prevent the process from exiting and logs a message when SIGINT is received. Note that installing a listener removes the default behavior of SIGINT on non-Windows platforms. ```javascript // Begin reading from stdin so the process does not exit. process.stdin.resume(); process.on('SIGINT', () => { console.log('Received SIGINT. Press Control-D to exit.'); }); ``` -------------------------------- ### repl.start() - Expose variable to REPL context Source: https://nodejs.org/docs/v8.5.0/api/all.html Shows how to use repl.start() and assign a property to the context object to expose a variable in the REPL. ```APIDOC ## repl.start() - Expose variable to REPL context ### Description Starts a REPL server and exposes a variable to the REPL context by assigning it to the `context` object. ### Method `repl.start()` ### Parameters - **options** (object) - Optional - Configuration options for the REPL server. In the example, `prompt` is set to `'> '`. ### Request Example ```javascript const repl = require('repl'); const msg = 'message'; repl.start('> ').context.m = msg; ``` ### Response #### Success Response - **REPLServer** - The started REPL server instance. #### Response Example ``` $ node repl_test.js > m 'message' ``` ``` -------------------------------- ### server.listen(options[, callback]) Source: https://nodejs.org/docs/v8.5.0/api/all.html Starts a server listening for connections using the specified options object. Options can include port, host, path, backlog, and exclusive. The callback is invoked when the server is bound. ```APIDOC ## server.listen(options[, callback]) ### Description Starts a server listening for connections using the specified options object. Options can include port, host, path, backlog, and exclusive. The callback is invoked when the server is bound. ### Method listen ### Parameters - **options** (Object) - Required - Configuration options for listening. - **callback** (Function) - Optional - Called when the server is bound. ### Response No return value. ``` -------------------------------- ### process.argv0 example: custom argv0 Source: https://nodejs.org/docs/v8.5.0/api/all.html Shows how process.argv0 stores the original value of argv[0] passed when Node.js starts, even when a custom argument is used via exec -a. The output demonstrates the difference between process.argv[0] and process.argv0. ```bash $ bash -c 'exec -a customArgv0 ./node' > process.argv[0] '/Volumes/code/external/node/out/Release/node' > process.argv0 'customArgv0' ``` -------------------------------- ### Create an HTTP/2 request with http2session.request() Source: https://nodejs.org/docs/v8.5.0/api/all.html Creates an Http2Stream for sending an HTTP/2 request to a connected server. Only available for client sessions (http2session.type equals NGHTTP2_SESSION_CLIENT). The example connects to a local HTTPS server, sends a GET request, and logs the response status. ```javascript const http2 = require('http2'); const clientSession = http2.connect('https://localhost:1234'); const { HTTP2_HEADER_PATH, HTTP2_HEADER_STATUS } = http2.constants; const req = clientSession.request({ [HTTP2_HEADER_PATH]: '/' }); req.on('response', (headers) => { console.log(HTTP2_HEADER_STATUS); req.on('data', (chunk) => { /** .. **/ }); req.on('end', () => { /** .. **/ }); }); ``` -------------------------------- ### Client request example: decompress HTTP response with zlib Source: https://nodejs.org/docs/v8.5.0/api/all.html Shows how to make an HTTP GET request with an Accept-Encoding header and decompress the response based on the Content-Encoding header. Uses zlib.createGunzip() for gzip and zlib.createInflate() for deflate. The comment notes that zlib.createUnzip() can handle both cases. ```javascript // client request example const zlib = require('zlib'); const http = require('http'); const fs = require('fs'); const request = http.get({ host: 'example.com', path: '/', port: 80, headers: { 'Accept-Encoding': 'gzip,deflate' } }); request.on('response', (response) => { const output = fs.createWriteStream('example.com_index.html'); switch (response.headers['content-encoding']) { // or, just use zlib.createUnzip() to handle both cases case 'gzip': response.pipe(zlib.createGunzip()).pipe(output); break; case 'deflate': response.pipe(zlib.createInflate()).pipe(output); break; default: response.pipe(output); break; } }); ``` -------------------------------- ### Using the Console class Source: https://nodejs.org/docs/v8.5.0/api/all.html Shows how to create a Console instance with custom output and error streams, then use its log, error, and warn methods. ```javascript const out = getStreamSomehow(); const err = getStreamSomehow(); const myConsole = new console.Console(out, err); myConsole.log('hello world'); // Prints: hello world, to out myConsole.log('hello %s', 'world'); // Prints: hello world, to out myConsole.error(new Error('Whoops, something bad happened')); // Prints: [Error: Whoops, something bad happened], to err const name = 'Will Robinson'; myConsole.warn(`Danger ${name}! Danger!`); // Prints: Danger Will Robinson! Danger!, to err ``` -------------------------------- ### Cluster example: master forks workers sharing an HTTP server Source: https://nodejs.org/docs/v8.5.0/api/all.html Shows how to use the cluster module to fork a worker per CPU and share an HTTP server on port 8000. The master logs its PID and worker exit events; workers create the server and log their start. Run with `node server.js`. ```javascript const cluster = require('cluster'); const http = require('http'); const numCPUs = require('os').cpus().length; if (cluster.isMaster) { console.log(`Master ${process.pid} is running`); // Fork workers. for (let i = 0; i < numCPUs; i++) { cluster.fork(); } cluster.on('exit', (worker, code, signal) => { console.log(`worker ${worker.process.pid} died`); }); } else { // Workers can share any TCP connection // In this case it is an HTTP server http.createServer((req, res) => { res.writeHead(200); res.end('hello world\n'); }).listen(8000); console.log(`Worker ${process.pid} started`); } ``` ```bash $ node server.js Master 3596 is running Worker 4324 started Worker 4520 started Worker 6056 started Worker 5644 started ``` -------------------------------- ### Output of process.argv example Source: https://nodejs.org/docs/v8.5.0/api/all.html Shows the expected output when running the process-args.js script with the given arguments. ```text 0: /usr/local/bin/node 1: /Users/mjr/work/node/process-args.js 2: one 3: two=three 4: four ``` -------------------------------- ### Starting multiple REPL instances on stdin, Unix socket, and TCP socket Source: https://nodejs.org/docs/v8.5.0/api/all.html This example creates three REPL instances sharing a single global object: one on stdin, one on a Unix socket, and one on a TCP socket. It uses the 'repl' and 'net' modules. The Unix socket listens on '/tmp/node-repl-sock' and the TCP socket on port 5001. Clients like telnet or socat can connect to these sockets. ```javascript const net = require('net'); const repl = require('repl'); let connections = 0; repl.start({ prompt: 'Node.js via stdin> ', input: process.stdin, output: process.stdout }); net.createServer((socket) => { connections += 1; repl.start({ prompt: 'Node.js via Unix socket> ', input: socket, output: socket }).on('exit', () => { socket.end(); }); }).listen('/tmp/node-repl-sock'); net.createServer((socket) => { connections += 1; repl.start({ prompt: 'Node.js via TCP socket> ', input: socket, output: socket }).on('exit', () => { socket.end(); }); }).listen(5001); ``` -------------------------------- ### Event: 'setup' Source: https://nodejs.org/docs/v8.5.0/api/all.html Emitted every time .setupMaster() is called. The settings object is the cluster.settings object at the time .setupMaster() was called and is advisory only. ```APIDOC ## Event: 'setup' ### Description Emitted every time `.setupMaster()` is called. The `settings` object is the `cluster.settings` object at the time `.setupMaster()` was called and is advisory only, since multiple calls to `.setupMaster()` can be made in a single tick. If accuracy is important, use `cluster.settings`. ### Event `setup` ### Parameters - `settings` (Object) - The `cluster.settings` object at the time `.setupMaster()` was called. ``` -------------------------------- ### ERR_INVALID_THIS Example Source: https://nodejs.org/docs/v8.5.0/api/all.html Example demonstrating the ERR_INVALID_THIS error when calling a Node.js API with an incompatible 'this' value. ```APIDOC ## ERR_INVALID_THIS ### Description Used generically to identify that a Node.js API function is called with an incompatible `this` value. ### Example ```javascript const { URLSearchParams } = require('url'); const urlSearchParams = new URLSearchParams('foo=bar&baz=new'); const buf = Buffer.alloc(1); urlSearchParams.has.call(buf, 'foo'); // Throws a TypeError with code 'ERR_INVALID_THIS' ``` ``` -------------------------------- ### cluster.setupMaster() example Source: https://nodejs.org/docs/v8.5.0/api/all.html Shows how to use cluster.setupMaster() to change the exec, args, and silent settings for subsequent cluster.fork() calls. The first fork uses the 'https' argument, the second uses 'http'. Only affects future forks, not already running workers. ```javascript const cluster = require('cluster'); cluster.setupMaster({ exec: 'worker.js', args: ['--use', 'https'], silent: true }); cluster.fork(); // https worker cluster.setupMaster({ exec: 'worker.js', args: ['--use', 'http'] }); cluster.fork(); // http worker ```