Lines Matching full:join
34068 "desc": "<p>Synchronously calls each of the listeners registered for the event named\n<code>eventName</code>, in the order they were registered, passing the supplied arguments\nto each.</p>\n<p>Returns <code>true</code> if the event had listeners, <code>false</code> otherwise.</p>\n<pre><code class=\"language-mjs\">import { EventEmitter } from 'node:events';\nconst myEmitter = new EventEmitter();\n\n// First listener\nmyEmitter.on('event', function firstListener() {\n console.log('Helloooo! first listener');\n});\n// Second listener\nmyEmitter.on('event', function secondListener(arg1, arg2) {\n console.log(`event with parameters ${arg1}, ${arg2} in second listener`);\n});\n// Third listener\nmyEmitter.on('event', function thirdListener(...args) {\n const parameters = args.join(', ');\n console.log(`event with parameters ${parameters} in third listener`);\n});\n\nconsole.log(myEmitter.listeners('event'));\n\nmyEmitter.emit('event', 1, 2, 3, 4, 5);\n\n// Prints:\n// [\n// [Function: firstListener],\n// [Function: secondListener],\n// [Function: thirdListener]\n// ]\n// Helloooo! first listener\n// event with parameters 1, 2 in second listener\n// event with parameters 1, 2, 3, 4, 5 in third listener\n</code></pre>\n<pre><code class=\"language-cjs\">const EventEmitter = require('node:events');\nconst myEmitter = new EventEmitter();\n\n// First listener\nmyEmitter.on('event', function firstListener() {\n console.log('Helloooo! first listener');\n});\n// Second listener\nmyEmitter.on('event', function secondListener(arg1, arg2) {\n console.log(`event with parameters ${arg1}, ${arg2} in second listener`);\n});\n// Third listener\nmyEmitter.on('event', function thirdListener(...args) {\n const parameters = args.join(', ');\n console.log(`event with parameters ${parameters} in third listener`);\n});\n\nconsole.log(myEmitter.listeners('event'));\n\nmyEmitter.emit('event', 1, 2, 3, 4, 5);\n\n// Prints:\n// [\n// [Function: firstListener],\n// [Function: secondListener],\n// [Function: thirdListener]\n// ]\n// Helloooo! first listener\n// event with parameters 1, 2 in second listener\n// event with parameters 1, 2, 3, 4, 5 in third listener\n</code></pre>"
36751 "desc": "<p>Asynchronously creates a directory.</p>\n<p>The optional <code>options</code> argument can be an integer specifying <code>mode</code> (permission\nand sticky bits), or an object with a <code>mode</code> property and a <code>recursive</code>\nproperty indicating whether parent directories should be created. Calling\n<code>fsPromises.mkdir()</code> when <code>path</code> is a directory that exists results in a\nrejection only when <code>recursive</code> is false.</p>\n<pre><code class=\"language-mjs\">import { mkdir } from 'node:fs/promises';\n\ntry {\n const projectFolder = new URL('./test/project/', import.meta.url);\n const createDir = await mkdir(projectFolder, { recursive: true });\n\n console.log(`created ${createDir}`);\n} catch (err) {\n console.error(err.message);\n}\n</code></pre>\n<pre><code class=\"language-cjs\">const { mkdir } = require('node:fs/promises');\nconst { join } = require('node:path');\n\nasync function makeDirectory() {\n const projectFolder = join(__dirname, 'test', 'project');\n const dirCreation = await mkdir(projectFolder, { recursive: true });\n\n console.log(dirCreation);\n return dirCreation;\n}\n\nmakeDirectory().catch(console.error);\n</code></pre>"
36807 "desc": "<p>Creates a unique temporary directory. A unique directory name is generated by\nappending six random characters to the end of the provided <code>prefix</code>. Due to\nplatform inconsistencies, avoid trailing <code>X</code> characters in <code>prefix</code>. Some\nplatforms, notably the BSDs, can return more than six random characters, and\nreplace trailing <code>X</code> characters in <code>prefix</code> with random characters.</p>\n<p>The optional <code>options</code> argument can be a string specifying an encoding, or an\nobject with an <code>encoding</code> property specifying the character encoding to use.</p>\n<pre><code class=\"language-mjs\">import { mkdtemp } from 'node:fs/promises';\nimport { join } from 'node:path';\nimport { tmpdir } from 'node:os';\n\ntry {\n await mkdtemp(join(tmpdir(), 'foo-'));\n} catch (err) {\n console.error(err);\n}\n</code></pre>\n<p>The <code>fsPromises.mkdtemp()</code> method will append the six randomly selected\ncharacters directly to the <code>prefix</code> string. For instance, given a directory\n<code>/tmp</code>, if the intention is to create a temporary directory <em>within</em> <code>/tmp</code>, the\n<code>prefix</code> must end with a trailing platform-specific path separator\n(<code>require('node:path').sep</code>).</p>"
39569 "desc": "<p>Creates a unique temporary directory.</p>\n<p>Generates six random characters to be appended behind a required\n<code>prefix</code> to create a unique temporary directory. Due to platform\ninconsistencies, avoid trailing <code>X</code> characters in <code>prefix</code>. Some platforms,\nnotably the BSDs, can return more than six random characters, and replace\ntrailing <code>X</code> characters in <code>prefix</code> with random characters.</p>\n<p>The created directory path is passed as a string to the callback's second\nparameter.</p>\n<p>The optional <code>options</code> argument can be a string specifying an encoding, or an\nobject with an <code>encoding</code> property specifying the character encoding to use.</p>\n<pre><code class=\"language-mjs\">import { mkdtemp } from 'node:fs';\nimport { join } from 'node:path';\nimport { tmpdir } from 'node:os';\n\nmkdtemp(join(tmpdir(), 'foo-'), (err, directory) => {\n if (err) throw err;\n console.log(directory);\n // Prints: /tmp/foo-itXde2 or C:\\Users\\...\\AppData\\Local\\Temp\\foo-itXde2\n});\n</code></pre>\n<p>The <code>fs.mkdtemp()</code> method will append the six randomly selected characters\ndirectly to the <code>prefix</code> string. For instance, given a directory <code>/tmp</code>, if the\nintention is to create a temporary directory <em>within</em> <code>/tmp</code>, the <code>prefix</code>\nmust end with a trailing platform-specific path separator\n(<code>require('node:path').sep</code>).</p>\n<pre><code class=\"language-mjs\">import { tmpdir } from 'node:os';\nimport { mkdtemp } from 'node:fs';\n\n// The parent directory for the new temporary directory\nconst tmpDir = tmpdir();\n\n// This method is *INCORRECT*:\nmkdtemp(tmpDir, (err, directory) => {\n if (err) throw err;\n console.log(directory);\n // Will print something similar to `/tmpabc123`.\n // A new temporary directory is created at the file system root\n // rather than *within* the /tmp directory.\n});\n\n// This method is *CORRECT*:\nimport { sep } from 'node:path';\nmkdtemp(`${tmpDir}${sep}`, (err, directory) => {\n if (err) throw err;\n console.log(directory);\n // Will print something similar to `/tmp/abc123`.\n // A new temporary directory is created within\n // the /tmp directory.\n});\n</code></pre>"
48180 "desc": "<p>Similar to <a href=\"http.html#messageheaders\"><code>message.headers</code></a>, but there is no join logic and the values are\nalways arrays of strings, even for headers received just once.</p>\n<pre><code class=\"language-js\">// Prints something like:\n//\n// { 'user-agent': ['curl/7.22.0'],\n// host: ['127.0.0.1:8000'],\n// accept: ['*/*'] }\nconsole.log(request.headersDistinct);\n</code></pre>"
48288 "desc": "<p>Similar to <a href=\"http.html#messagetrailers\"><code>message.trailers</code></a>, but there is no join logic and the values are\nalways arrays of strings, even for headers received just once.\nOnly populated at the <code>'end'</code> event.</p>"
55022 "desc": "<p>To get the exact filename that will be loaded when <code>require()</code> is called, use\nthe <code>require.resolve()</code> function.</p>\n<p>Putting together all of the above, here is the high-level algorithm\nin pseudocode of what <code>require()</code> does:</p>\n<pre>\nrequire(X) from module at path Y\n1. If X is a core module,\n a. return the core module\n b. STOP\n2. If X begins with '/'\n a. set Y to be the file system root\n3. If X begins with './' or '/' or '../'\n a. LOAD_AS_FILE(Y + X)\n b. LOAD_AS_DIRECTORY(Y + X)\n c. THROW \"not found\"\n4. If X begins with '#'\n a. LOAD_PACKAGE_IMPORTS(X, dirname(Y))\n5. LOAD_PACKAGE_SELF(X, dirname(Y))\n6. LOAD_NODE_MODULES(X, dirname(Y))\n7. THROW \"not found\"\n\nLOAD_AS_FILE(X)\n1. If X is a file, load X as its file extension format. STOP\n2. If X.js is a file, load X.js as JavaScript text. STOP\n3. If X.json is a file, parse X.json to a JavaScript Object. STOP\n4. If X.node is a file, load X.node as binary addon. STOP\n\nLOAD_INDEX(X)\n1. If X/index.js is a file, load X/index.js as JavaScript text. STOP\n2. If X/index.json is a file, parse X/index.json to a JavaScript object. STOP\n3. If X/index.node is a file, load X/index.node as binary addon. STOP\n\nLOAD_AS_DIRECTORY(X)\n1. If X/package.json is a file,\n a. Parse X/package.json, and look for \"main\" field.\n b. If \"main\" is a falsy value, GOTO 2.\n c. let M = X + (json main field)\n d. LOAD_AS_FILE(M)\n e. LOAD_INDEX(M)\n f. LOAD_INDEX(X) DEPRECATED\n g. THROW \"not found\"\n2. LOAD_INDEX(X)\n\nLOAD_NODE_MODULES(X, START)\n1. let DIRS = NODE_MODULES_PATHS(START)\n2. for each DIR in DIRS:\n a. LOAD_PACKAGE_EXPORTS(X, DIR)\n b. LOAD_AS_FILE(DIR/X)\n c. LOAD_AS_DIRECTORY(DIR/X)\n\nNODE_MODULES_PATHS(START)\n1. let PARTS = path split(START)\n2. let I = count of PARTS - 1\n3. let DIRS = []\n4. while I >= 0,\n a. if PARTS[I] = \"node_modules\" CONTINUE\n b. DIR = path join(PARTS[0 .. I] + \"node_modules\")\n c. DIRS = DIR + DIRS\n d. let I = I - 1\n5. return DIRS + GLOBAL_FOLDERS\n\nLOAD_PACKAGE_IMPORTS(X, DIR)\n1. Find the closest package scope SCOPE to DIR.\n2. If no scope was found, return.\n3. If the SCOPE/package.json \"imports\" is null or undefined, return.\n4. let MATCH = PACKAGE_IMPORTS_RESOLVE(X, pathToFileURL(SCOPE),\n [\"node\", \"require\"]) <a href=\"esm.md#resolver-algorithm-specification\">defined in the ESM resolver</a>.\n5. RESOLVE_ESM_MATCH(MATCH).\n\nLOAD_PACKAGE_EXPORTS(X, DIR)\n1. Try to interpret X as a combination of NAME and SUBPATH where the name\n may have a @scope/ prefix and the subpath begins with a slash (`/`).\n2. If X does not match this pattern or DIR/NAME/package.json is not a file,\n return.\n3. Parse DIR/NAME/package.json, and look for \"exports\" field.\n4. If \"exports\" is null or undefined, return.\n5. let MATCH = PACKAGE_EXPORTS_RESOLVE(pathToFileURL(DIR/NAME), \".\" + SUBPATH,\n `package.json` \"exports\", [\"node\", \"require\"]) <a href=\"esm.md#resolver-algorithm-specification\">defined in the ESM resolver</a>.\n6. RESOLVE_ESM_MATCH(MATCH)\n\nLOAD_PACKAGE_SELF(X, DIR)\n1. Find the closest package scope SCOPE to DIR.\n2. If no scope was found, return.\n3. If the SCOPE/package.json \"exports\" is null or undefined, return.\n4. If the SCOPE/package.json \"name\" is not the first segment of X, return.\n5. let MATCH = PACKAGE_EXPORTS_RESOLVE(pathToFileURL(SCOPE),\n \".\" + X.slice(\"name\".length), `package.json` \"exports\", [\"node\", \"require\"])\n <a href=\"esm.md#resolver-algorithm-specification\">defined in the ESM resolver</a>.\n6. RESOLVE_ESM_MATCH(MATCH)\n\nRESOLVE_ESM_MATCH(MATCH)\n1. let RESOLVED_PATH = fileURLToPath(MATCH)\n2. If the file at RESOLVED_PATH exists, load RESOLVED_PATH as its extension\n format. STOP\n3. THROW \"not found\"\n</pre>"
56196 "desc": "<p><a href=\"net.html#netconnect\"><code>net.connect()</code></a>, <a href=\"net.html#netcreateconnection\"><code>net.createConnection()</code></a>, <a href=\"net.html#serverlisten\"><code>server.listen()</code></a>, and\n<a href=\"net.html#socketconnect\"><code>socket.connect()</code></a> take a <code>path</code> parameter to identify IPC endpoints.</p>\n<p>On Unix, the local domain is also known as the Unix domain. The path is a\nfile system pathname. It gets truncated to an OS-dependent length of\n<code>sizeof(sockaddr_un.sun_path) - 1</code>. Typical values are 107 bytes on Linux and\n103 bytes on macOS. If a Node.js API abstraction creates the Unix domain socket,\nit will unlink the Unix domain socket as well. For example,\n<a href=\"net.html#netcreateserveroptions-connectionlistener\"><code>net.createServer()</code></a> may create a Unix domain socket and\n<a href=\"net.html#serverclosecallback\"><code>server.close()</code></a> will unlink it. But if a user creates the Unix domain\nsocket outside of these abstractions, the user will need to remove it. The same\napplies when a Node.js API creates a Unix domain socket but the program then\ncrashes. In short, a Unix domain socket will be visible in the file system and\nwill persist until unlinked.</p>\n<p>On Windows, the local domain is implemented using a named pipe. The path <em>must</em>\nrefer to an entry in <code>\\\\?\\pipe\\</code> or <code>\\\\.\\pipe\\</code>. Any characters are permitted,\nbut the latter may do some processing of pipe names, such as resolving <code>..</code>\nsequences. Despite how it might look, the pipe namespace is flat. Pipes will\n<em>not persist</em>. They are removed when the last reference to them is closed.\nUnlike Unix domain sockets, Windows will close and remove the pipe when the\nowning process exits.</p>\n<p>JavaScript string escaping requires paths to be specified with extra backslash\nescaping such as:</p>\n<pre><code class=\"language-js\">net.createServer().listen(\n path.join('\\\\\\\\?\\\\pipe', process.cwd(), 'myctl'));\n</code></pre>",
59298 "textRaw": "`path.join([...paths])`",
59300 "name": "join",
59324 "desc": "<p>The <code>path.join()</code> method joins all given <code>path</code> segments together using the\nplatform-specific separator as a delimiter, then normalizes the resulting path.</p>\n<p>Zero-length <code>path</code> segments are ignored. If the joined path string is a\nzero-length string then <code>'.'</code> will be returned, representing the current\nworking directory.</p>\n<pre><code class=\"language-js\">path.join('/foo', 'bar', 'baz/asdf', 'quux', '..');\n// Returns: '/foo/bar/baz/asdf'\n\npath.join('foo', {}, 'bar');\n// Throws 'TypeError: Path must be a string. Received {}'\n</code></pre>\n<p>A <a href=\"errors.html#class-typeerror\"><code>TypeError</code></a> is thrown if any of the path segments is not a string.</p>"
62207 "desc": "<p>The current input data being processed by node.</p>\n<p>This can be used when collecting input from a TTY stream to retrieve the\ncurrent value that has been processed thus far, prior to the <code>line</code> event\nbeing emitted. Once the <code>line</code> event has been emitted, this property will\nbe an empty string.</p>\n<p>Be aware that modifying the value during the instance runtime may have\nunintended consequences if <code>rl.cursor</code> is not also controlled.</p>\n<p><strong>If not using a TTY stream for input, use the <a href=\"readline.html#event-line\"><code>'line'</code></a> event.</strong></p>\n<p>One possible use case would be as follows:</p>\n<pre><code class=\"language-js\">const values = ['lorem ipsum', 'dolor sit amet'];\nconst rl = readline.createInterface(process.stdin);\nconst showResults = debounce(() => {\n console.log(\n '\\n',\n values.filter((val) => val.startsWith(rl.line)).join(' '),\n );\n}, 300);\nprocess.stdin.on('keypress', (c, k) => {\n showResults();\n});\n</code></pre>"
65770 "desc": "<p>The <code>readable.read()</code> method reads data out of the internal buffer and\nreturns it. If no data is available to be read, <code>null</code> is returned. By default,\nthe data is returned as a <code>Buffer</code> object unless an encoding has been\nspecified using the <code>readable.setEncoding()</code> method or the stream is operating\nin object mode.</p>\n<p>The optional <code>size</code> argument specifies a specific number of bytes to read. If\n<code>size</code> bytes are not available to be read, <code>null</code> will be returned <em>unless</em>\nthe stream has ended, in which case all of the data remaining in the internal\nbuffer will be returned.</p>\n<p>If the <code>size</code> argument is not specified, all of the data contained in the\ninternal buffer will be returned.</p>\n<p>The <code>size</code> argument must be less than or equal to 1 GiB.</p>\n<p>The <code>readable.read()</code> method should only be called on <code>Readable</code> streams\noperating in paused mode. In flowing mode, <code>readable.read()</code> is called\nautomatically until the internal buffer is fully drained.</p>\n<pre><code class=\"language-js\">const readable = getReadableStreamSomehow();\n\n// 'readable' may be triggered multiple times as data is buffered in\nreadable.on('readable', () => {\n let chunk;\n console.log('Stream is readable (new data received in buffer)');\n // Use a loop to make sure we read all currently available data\n while (null !== (chunk = readable.read())) {\n console.log(`Read ${chunk.length} bytes of data...`);\n }\n});\n\n// 'end' will be triggered once when there is no more data available\nreadable.on('end', () => {\n console.log('Reached end of stream.');\n});\n</code></pre>\n<p>Each call to <code>readable.read()</code> returns a chunk of data, or <code>null</code>. The chunks\nare not concatenated. A <code>while</code> loop is necessary to consume all data\ncurrently in the buffer. When reading a large file <code>.read()</code> may return <code>null</code>,\nhaving consumed all buffered content so far, but there is still more data to\ncome not yet buffered. In this case a new <code>'readable'</code> event will be emitted\nwhen there is more data in the buffer. Finally the <code>'end'</code> event will be\nemitted when there is no more data to come.</p>\n<p>Therefore to read a file's whole contents from a <code>readable</code>, it is necessary\nto collect chunks across multiple <code>'readable'</code> events:</p>\n<pre><code class=\"language-js\">const chunks = [];\n\nreadable.on('readable', () => {\n let chunk;\n while (null !== (chunk = readable.read())) {\n chunks.push(chunk);\n }\n});\n\nreadable.on('end', () => {\n const content = chunks.join('');\n});\n</code></pre>\n<p>A <code>Readable</code> stream in object mode will always return a single item from\na call to <a href=\"stream.html#readablereadsize\"><code>readable.read(size)</code></a>, regardless of the value of the\n<code>size</code> argument.</p>\n<p>If the <code>readable.read()</code> method returns a chunk of data, a <code>'data'</code> event will\nalso be emitted.</p>\n<p>Calling <a href=\"stream.html#readablereadsize\"><code>stream.read([size])</code></a> after the <a href=\"stream.html#event-end\"><code>'end'</code></a> event has\nbeen emitted will return <code>null</code>. No runtime error will be raised.</p>"
65892 "desc": "<p>Passing <code>chunk</code> as <code>null</code> signals the end of the stream (EOF) and behaves the\nsame as <code>readable.push(null)</code>, after which no more data can be written. The EOF\nsignal is put at the end of the buffer and any buffered data will still be\nflushed.</p>\n<p>The <code>readable.unshift()</code> method pushes a chunk of data back into the internal\nbuffer. This is useful in certain situations where a stream is being consumed by\ncode that needs to \"un-consume\" some amount of data that it has optimistically\npulled out of the source, so that the data can be passed on to some other party.</p>\n<p>The <code>stream.unshift(chunk)</code> method cannot be called after the <a href=\"stream.html#event-end\"><code>'end'</code></a> event\nhas been emitted or a runtime error will be thrown.</p>\n<p>Developers using <code>stream.unshift()</code> often should consider switching to\nuse of a <a href=\"stream.html#class-streamtransform\"><code>Transform</code></a> stream instead. See the <a href=\"stream.html#api-for-stream-implementers\">API for stream implementers</a>\nsection for more information.</p>\n<pre><code class=\"language-js\">// Pull off a header delimited by \\n\\n.\n// Use unshift() if we get too much.\n// Call the callback with (error, header, stream).\nconst { StringDecoder } = require('node:string_decoder');\nfunction parseHeader(stream, callback) {\n stream.on('error', callback);\n stream.on('readable', onReadable);\n const decoder = new StringDecoder('utf8');\n let header = '';\n function onReadable() {\n let chunk;\n while (null !== (chunk = stream.read())) {\n const str = decoder.write(chunk);\n if (str.includes('\\n\\n')) {\n // Found the header boundary.\n const split = str.split(/\\n\\n/);\n header += split.shift();\n const remaining = split.join('\\n\\n');\n const buf = Buffer.from(remaining, 'utf8');\n stream.removeListener('error', callback);\n // Remove the 'readable' listener before unshifting.\n stream.removeListener('readable', onReadable);\n if (buf.length)\n stream.unshift(buf);\n // Now the body of the message can be read from the stream.\n callback(null, header, stream);\n return;\n }\n // Still reading the header.\n header += str;\n }\n }\n}\n</code></pre>\n<p>Unlike <a href=\"stream.html#readablepushchunk-encoding\"><code>stream.push(chunk)</code></a>, <code>stream.unshift(chunk)</code> will not\nend the reading process by resetting the internal reading state of the stream.\nThis can cause unexpected results if <code>readable.unshift()</code> is called during a\nread (i.e. from within a <a href=\"stream.html#readable_readsize\"><code>stream._read()</code></a> implementation on a\ncustom stream). Following the call to <code>readable.unshift()</code> with an immediate\n<a href=\"stream.html#readablepushchunk-encoding\"><code>stream.push('')</code></a> will reset the reading state appropriately,\nhowever it is best to simply avoid calling <code>readable.unshift()</code> while in the\nprocess of performing a read.</p>"
66844 "desc": "<p>This method calls <code>fn</code> on each chunk of the stream in order, passing it the\nresult from the calculation on the previous element. It returns a promise for\nthe final value of the reduction.</p>\n<p>If no <code>initial</code> value is supplied the first chunk of the stream is used as the\ninitial value. If the stream is empty, the promise is rejected with a\n<code>TypeError</code> with the <code>ERR_INVALID_ARGS</code> code property.</p>\n<pre><code class=\"language-mjs\">import { Readable } from 'node:stream';\nimport { readdir, stat } from 'node:fs/promises';\nimport { join } from 'node:path';\n\nconst directoryPath = './src';\nconst filesInDir = await readdir(directoryPath);\n\nconst folderSize = await Readable.from(filesInDir)\n .reduce(async (totalSize, file) => {\n const { size } = await stat(join(directoryPath, file));\n return totalSize + size;\n }, 0);\n\nconsole.log(folderSize);\n</code></pre>\n<p>The reducer function iterates the stream element-by-element which means that\nthere is no <code>concurrency</code> parameter or parallelism. To perform a <code>reduce</code>\nconcurrently, you can extract the async function to <a href=\"stream.html#readablemapfn-options\"><code>readable.map</code></a> method.</p>\n<pre><code class=\"language-mjs\">import { Readable } from 'node:stream';\nimport { readdir, stat } from 'node:fs/promises';\nimport { join } from 'node:path';\n\nconst directoryPath = './src';\nconst filesInDir = await readdir(directoryPath);\n\nconst folderSize = await Readable.from(filesInDir)\n .map((file) => stat(join(directoryPath, file)), { concurrency: 2 })\n .reduce((totalSize, { size }) => totalSize + size, 0);\n\nconsole.log(folderSize);\n</code></pre>"
74975 "desc": "<p>Tells the kernel to join a multicast group at the given <code>multicastAddress</code> and\n<code>multicastInterface</code> using the <code>IP_ADD_MEMBERSHIP</code> socket option. If the\n<code>multicastInterface</code> argument is not specified, the operating system will choose\none interface and will add membership to it. To add membership to every\navailable interface, call <code>addMembership</code> multiple times, once per interface.</p>\n<p>When called on an unbound socket, this method will implicitly bind to a random\nport, listening on all interfaces.</p>\n<p>When sharing a UDP socket across multiple <code>cluster</code> workers, the\n<code>socket.addMembership()</code> function must be called only once or an\n<code>EADDRINUSE</code> error will occur:</p>\n<pre><code class=\"language-mjs\">import cluster from 'node:cluster';\nimport dgram from 'node:dgram';\n\nif (cluster.isPrimary) {\n cluster.fork(); // Works ok.\n cluster.fork(); // Fails with EADDRINUSE.\n} else {\n const s = dgram.createSocket('udp4');\n s.bind(1234, () => {\n s.addMembership('224.0.0.114');\n });\n}\n</code></pre>\n<pre><code class=\"language-cjs\">const cluster = require('node:cluster');\nconst dgram = require('node:dgram');\n\nif (cluster.isPrimary) {\n cluster.fork(); // Works ok.\n cluster.fork(); // Fails with EADDRINUSE.\n} else {\n const s = dgram.createSocket('udp4');\n s.bind(1234, () => {\n s.addMembership('224.0.0.114');\n });\n}\n</code></pre>"
75009 "desc": "<p>Tells the kernel to join a source-specific multicast channel at the given\n<code>sourceAddress</code> and <code>groupAddress</code>, using the <code>multicastInterface</code> with the\n<code>IP_ADD_SOURCE_MEMBERSHIP</code> socket option. If the <code>multicastInterface</code> argument\nis not specified, the operating system will choose one interface and will add\nmembership to it. To add membership to every available interface, call\n<code>socket.addSourceSpecificMembership()</code> multiple times, once per interface.</p>\n<p>When called on an unbound socket, this method will implicitly bind to a random\nport, listening on all interfaces.</p>"
78186 "desc": "<p>Provides a higher level API for command-line argument parsing than interacting\nwith <code>process.argv</code> directly. Takes a specification for the expected arguments\nand returns a structured object with the parsed options and positionals.</p>\n<pre><code class=\"language-mjs\">import { parseArgs } from 'node:util';\nconst args = ['-f', '--bar', 'b'];\nconst options = {\n foo: {\n type: 'boolean',\n short: 'f',\n },\n bar: {\n type: 'string',\n },\n};\nconst {\n values,\n positionals,\n} = parseArgs({ args, options });\nconsole.log(values, positionals);\n// Prints: [Object: null prototype] { foo: true, bar: 'b' } []\n</code></pre>\n<pre><code class=\"language-cjs\">const { parseArgs } = require('node:util');\nconst args = ['-f', '--bar', 'b'];\nconst options = {\n foo: {\n type: 'boolean',\n short: 'f',\n },\n bar: {\n type: 'string',\n },\n};\nconst {\n values,\n positionals,\n} = parseArgs({ args, options });\nconsole.log(values, positionals);\n// Prints: [Object: null prototype] { foo: true, bar: 'b' } []\n</code></pre>\n<p><code>util.parseArgs</code> is experimental and behavior may change. Join the\nconversation in <a href=\"https://github.com/pkgjs/parseargs\">pkgjs/parseargs</a> to contribute to the design.</p>",
81687 "desc": "<p>The <code>v8.startupSnapshot</code> interface can be used to add serialization and\ndeserialization hooks for custom startup snapshots.</p>\n<pre><code class=\"language-console\">$ node --snapshot-blob snapshot.blob --build-snapshot entry.js\n# This launches a process with the snapshot\n$ node --snapshot-blob snapshot.blob\n</code></pre>\n<p>In the example above, <code>entry.js</code> can use methods from the <code>v8.startupSnapshot</code>\ninterface to specify how to save information for custom objects in the snapshot\nduring serialization and how the information can be used to synchronize these\nobjects during deserialization of the snapshot. For example, if the <code>entry.js</code>\ncontains the following script:</p>\n<pre><code class=\"language-cjs\">'use strict';\n\nconst fs = require('node:fs');\nconst zlib = require('node:zlib');\nconst path = require('node:path');\nconst assert = require('node:assert');\n\nconst v8 = require('node:v8');\n\nclass BookShelf {\n storage = new Map();\n\n // Reading a series of files from directory and store them into storage.\n constructor(directory, books) {\n for (const book of books) {\n this.storage.set(book, fs.readFileSync(path.join(directory, book)));\n }\n }\n\n static compressAll(shelf) {\n for (const [ book, content ] of shelf.storage) {\n shelf.storage.set(book, zlib.gzipSync(content));\n }\n }\n\n static decompressAll(shelf) {\n for (const [ book, content ] of shelf.storage) {\n shelf.storage.set(book, zlib.gunzipSync(content));\n }\n }\n}\n\n// __dirname here is where the snapshot script is placed\n// during snapshot building time.\nconst shelf = new BookShelf(__dirname, [\n 'book1.en_US.txt',\n 'book1.es_ES.txt',\n 'book2.zh_CN.txt',\n]);\n\nassert(v8.startupSnapshot.isBuildingSnapshot());\n// On snapshot serialization, compress the books to reduce size.\nv8.startupSnapshot.addSerializeCallback(BookShelf.compressAll, shelf);\n// On snapshot deserialization, decompress the books.\nv8.startupSnapshot.addDeserializeCallback(BookShelf.decompressAll, shelf);\nv8.startupSnapshot.setDeserializeMainFunction((shelf) => {\n // process.env and process.argv are refreshed during snapshot\n // deserialization.\n const lang = process.env.BOOK_LANG || 'en_US';\n const book = process.argv[1];\n const name = `${book}.${lang}.txt`;\n console.log(shelf.storage.get(name));\n}, shelf);\n</code></pre>\n<p>The resulted binary will get print the data deserialized from the snapshot\nduring start up, using the refreshed <code>process.env</code> and <code>process.argv</code> of\nthe launched process:</p>\n<pre><code class=\"language-console\">$ BOOK_LANG=es_ES node --snapshot-blob snapshot.blob book1\n# Prints content of book1.es_ES.txt deserialized from the snapshot.\n</code></pre>\n<p>Currently the application deserialized from a user-land snapshot cannot\nbe snapshotted again, so these APIs are only available to applications\nthat are not deserialized from a user-land snapshot.</p>",
83410 "desc": "<p><strong>Source Code:</strong> <a href=\"https://github.com/nodejs/node/blob/v18.20.1/lib/wasi.js\">lib/wasi.js</a></p>\n<p>The WASI API provides an implementation of the <a href=\"https://wasi.dev/\">WebAssembly System Interface</a>\nspecification. WASI gives sandboxed WebAssembly applications access to the\nunderlying operating system via a collection of POSIX-like functions.</p>\n<pre><code class=\"language-mjs\">import { readFile } from 'node:fs/promises';\nimport { WASI } from 'wasi';\nimport { argv, env } from 'node:process';\n\nconst wasi = new WASI({\n args: argv,\n env,\n preopens: {\n '/sandbox': '/some/real/path/that/wasm/can/access',\n },\n});\n\n// Some WASI binaries require:\n// const importObject = { wasi_unstable: wasi.wasiImport };\nconst importObject = { wasi_snapshot_preview1: wasi.wasiImport };\n\nconst wasm = await WebAssembly.compile(\n await readFile(new URL('./demo.wasm', import.meta.url)),\n);\nconst instance = await WebAssembly.instantiate(wasm, importObject);\n\nwasi.start(instance);\n</code></pre>\n<pre><code class=\"language-cjs\">'use strict';\nconst { readFile } = require('node:fs/promises');\nconst { WASI } = require('wasi');\nconst { argv, env } = require('node:process');\nconst { join } = require('node:path');\n\nconst wasi = new WASI({\n args: argv,\n env,\n preopens: {\n '/sandbox': '/some/real/path/that/wasm/can/access',\n },\n});\n\n// Some WASI binaries require:\n// const importObject = { wasi_unstable: wasi.wasiImport };\nconst importObject = { wasi_snapshot_preview1: wasi.wasiImport };\n\n(async () => {\n const wasm = await WebAssembly.compile(\n await readFile(join(__dirname, 'demo.wasm')),\n );\n const instance = await WebAssembly.instantiate(wasm, importObject);\n\n wasi.start(instance);\n})();\n</code></pre>\n<p>To run the above example, create a new WebAssembly text format file named\n<code>demo.wat</code>:</p>\n<pre><code class=\"language-text\">(module\n ;; Import the required fd_write WASI function which will write the given io vectors to stdout\n ;; The function signature for fd_write is:\n ;; (File Descriptor, *iovs, iovs_len, nwritten) -> Returns number of bytes written\n (import \"wasi_snapshot_preview1\" \"fd_write\" (func $fd_write (param i32 i32 i32 i32) (result i32)))\n\n (memory 1)\n (export \"memory\" (memory 0))\n\n ;; Write 'hello world\\n' to memory at an offset of 8 bytes\n ;; Note the trailing newline which is required for the text to appear\n (data (i32.const 8) \"hello world\\n\")\n\n (func $main (export \"_start\")\n ;; Creating a new io vector within linear memory\n (i32.store (i32.const 0) (i32.const 8)) ;; iov.iov_base - This is a pointer to the start of the 'hello world\\n' string\n (i32.store (i32.const 4) (i32.const 12)) ;; iov.iov_len - The length of the 'hello world\\n' string\n\n (call $fd_write\n (i32.const 1) ;; file_descriptor - 1 for stdout\n (i32.const 0) ;; *iovs - The pointer to the iov array, which is stored at memory location 0\n (i32.const 1) ;; iovs_len - We're printing 1 string stored in an iov - so one.\n (i32.const 20) ;; nwritten - A place in memory to store the number of bytes written\n )\n drop ;; Discard the number of bytes written from the top of the stack\n )\n)\n</code></pre>\n<p>Use <a href=\"https://github.com/WebAssembly/wabt\">wabt</a> to compile <code>.wat</code> to <code>.wasm</code></p>\n<pre><code class=\"language-console\">$ wat2wasm demo.wat\n</code></pre>",
92258 "desc": "<p>The <code>process.dlopen()</code> method allows dynamically loading shared objects. It is\nprimarily used by <code>require()</code> to load C++ Addons, and should not be used\ndirectly, except in special cases. In other words, <a href=\"globals.html#require\"><code>require()</code></a> should be\npreferred over <code>process.dlopen()</code> unless there are specific reasons such as\ncustom dlopen flags or loading from ES modules.</p>\n<p>The <code>flags</code> argument is an integer that allows to specify dlopen\nbehavior. See the <a href=\"os.html#dlopen-constants\"><code>os.constants.dlopen</code></a> documentation for details.</p>\n<p>An important requirement when calling <code>process.dlopen()</code> is that the <code>module</code>\ninstance must be passed. Functions exported by the C++ Addon are then\naccessible via <code>module.exports</code>.</p>\n<p>The example below shows how to load a C++ Addon, named <code>local.node</code>,\nthat exports a <code>foo</code> function. All the symbols are loaded before\nthe call returns, by passing the <code>RTLD_NOW</code> constant. In this example\nthe constant is assumed to be available.</p>\n<pre><code class=\"language-mjs\">import { dlopen } from 'node:process';\nimport { constants } from 'node:os';\nimport { fileURLToPath } from 'node:url';\n\nconst module = { exports: {} };\ndlopen(module, fileURLToPath(new URL('local.node', import.meta.url)),\n constants.dlopen.RTLD_NOW);\nmodule.exports.foo();\n</code></pre>\n<pre><code class=\"language-cjs\">const { dlopen } = require('node:process');\nconst { constants } = require('node:os');\nconst { join } = require('node:path');\n\nconst module = { exports: {} };\ndlopen(module, join(__dirname, 'local.node'), constants.dlopen.RTLD_NOW);\nmodule.exports.foo();\n</code></pre>"