content large_stringlengths 3 20.5k | url large_stringlengths 54 193 | branch large_stringclasses 4 values | source large_stringclasses 42 values | embeddings listlengths 384 384 | score float64 -0.21 0.65 |
|---|---|---|---|---|---|
= Buffer.allocUnsafe(2); buf.writeInt16LE(0x0304, 0); console.log(buf); // Prints: ``` ```cjs const { Buffer } = require('node:buffer'); const buf = Buffer.allocUnsafe(2); buf.writeInt16LE(0x0304, 0); console.log(buf); // Prints: ``` ### `buf.writeInt32BE(value[, offset])` \* `value` {integer} Number to be written to `buf`. \* `offset` {integer} Number of bytes to skip before starting to write. Must satisfy `0 <= offset <= buf.length - 4`. \*\*Default:\*\* `0`. \* Returns: {integer} `offset` plus the number of bytes written. Writes `value` to `buf` at the specified `offset` as big-endian. The `value` must be a valid signed 32-bit integer. Behavior is undefined when `value` is anything other than a signed 32-bit integer. The `value` is interpreted and written as a two's complement signed integer. ```mjs import { Buffer } from 'node:buffer'; const buf = Buffer.allocUnsafe(4); buf.writeInt32BE(0x01020304, 0); console.log(buf); // Prints: ``` ```cjs const { Buffer } = require('node:buffer'); const buf = Buffer.allocUnsafe(4); buf.writeInt32BE(0x01020304, 0); console.log(buf); // Prints: ``` ### `buf.writeInt32LE(value[, offset])` \* `value` {integer} Number to be written to `buf`. \* `offset` {integer} Number of bytes to skip before starting to write. Must satisfy `0 <= offset <= buf.length - 4`. \*\*Default:\*\* `0`. \* Returns: {integer} `offset` plus the number of bytes written. Writes `value` to `buf` at the specified `offset` as little-endian. The `value` must be a valid signed 32-bit integer. Behavior is undefined when `value` is anything other than a signed 32-bit integer. The `value` is interpreted and written as a two's complement signed integer. ```mjs import { Buffer } from 'node:buffer'; const buf = Buffer.allocUnsafe(4); buf.writeInt32LE(0x05060708, 0); console.log(buf); // Prints: ``` ```cjs const { Buffer } = require('node:buffer'); const buf = Buffer.allocUnsafe(4); buf.writeInt32LE(0x05060708, 0); console.log(buf); // Prints: ``` ### `buf.writeIntBE(value, offset, byteLength)` \* `value` {integer} Number to be written to `buf`. \* `offset` {integer} Number of bytes to skip before starting to write. Must satisfy `0 <= offset <= buf.length - byteLength`. \* `byteLength` {integer} Number of bytes to write. Must satisfy `0 < byteLength <= 6`. \* Returns: {integer} `offset` plus the number of bytes written. Writes `byteLength` bytes of `value` to `buf` at the specified `offset` as big-endian. Supports up to 48 bits of accuracy. Behavior is undefined when `value` is anything other than a signed integer. ```mjs import { Buffer } from 'node:buffer'; const buf = Buffer.allocUnsafe(6); buf.writeIntBE(0x1234567890ab, 0, 6); console.log(buf); // Prints: ``` ```cjs const { Buffer } = require('node:buffer'); const buf = Buffer.allocUnsafe(6); buf.writeIntBE(0x1234567890ab, 0, 6); console.log(buf); // Prints: ``` ### `buf.writeIntLE(value, offset, byteLength)` \* `value` {integer} Number to be written to `buf`. \* `offset` {integer} Number of bytes to skip before starting to write. Must satisfy `0 <= offset <= buf.length - byteLength`. \* `byteLength` {integer} Number of bytes to write. Must satisfy `0 < byteLength <= 6`. \* Returns: {integer} `offset` plus the number of bytes written. Writes `byteLength` bytes of `value` to `buf` at the specified `offset` as little-endian. Supports up to 48 bits of accuracy. Behavior is undefined when `value` is anything other than a signed integer. ```mjs import { Buffer } from 'node:buffer'; const buf = Buffer.allocUnsafe(6); buf.writeIntLE(0x1234567890ab, 0, 6); console.log(buf); // Prints: ``` ```cjs const { Buffer } = require('node:buffer'); const buf = Buffer.allocUnsafe(6); buf.writeIntLE(0x1234567890ab, 0, 6); console.log(buf); // Prints: ``` ### `buf.writeUInt8(value[, offset])` \* `value` {integer} Number to be written to `buf`. \* `offset` {integer} Number of bytes to skip before starting to write. Must satisfy `0 <= offset <= buf.length - 1`. \*\*Default:\*\* `0`. \* Returns: {integer} `offset` plus the number of bytes written. Writes `value` to `buf` at the specified `offset`. `value` must be a valid unsigned 8-bit integer. Behavior is undefined when `value` is anything other than an unsigned 8-bit integer. This | https://github.com/nodejs/node/blob/main//doc/api/buffer.md | main | nodejs | [
0.06705468147993088,
0.04310430958867073,
-0.044539403170347214,
-0.014204762876033783,
-0.037499941885471344,
-0.01953435130417347,
-0.025318056344985962,
0.08024797588586807,
-0.022499719634652138,
-0.027662398293614388,
-0.04679577052593231,
-0.03857496380805969,
-0.0579882375895977,
-0... | 0.100136 |
satisfy `0 <= offset <= buf.length - 1`. \*\*Default:\*\* `0`. \* Returns: {integer} `offset` plus the number of bytes written. Writes `value` to `buf` at the specified `offset`. `value` must be a valid unsigned 8-bit integer. Behavior is undefined when `value` is anything other than an unsigned 8-bit integer. This function is also available under the `writeUint8` alias. ```mjs import { Buffer } from 'node:buffer'; const buf = Buffer.allocUnsafe(4); buf.writeUInt8(0x3, 0); buf.writeUInt8(0x4, 1); buf.writeUInt8(0x23, 2); buf.writeUInt8(0x42, 3); console.log(buf); // Prints: ``` ```cjs const { Buffer } = require('node:buffer'); const buf = Buffer.allocUnsafe(4); buf.writeUInt8(0x3, 0); buf.writeUInt8(0x4, 1); buf.writeUInt8(0x23, 2); buf.writeUInt8(0x42, 3); console.log(buf); // Prints: ``` ### `buf.writeUInt16BE(value[, offset])` \* `value` {integer} Number to be written to `buf`. \* `offset` {integer} Number of bytes to skip before starting to write. Must satisfy `0 <= offset <= buf.length - 2`. \*\*Default:\*\* `0`. \* Returns: {integer} `offset` plus the number of bytes written. Writes `value` to `buf` at the specified `offset` as big-endian. The `value` must be a valid unsigned 16-bit integer. Behavior is undefined when `value` is anything other than an unsigned 16-bit integer. This function is also available under the `writeUint16BE` alias. ```mjs import { Buffer } from 'node:buffer'; const buf = Buffer.allocUnsafe(4); buf.writeUInt16BE(0xdead, 0); buf.writeUInt16BE(0xbeef, 2); console.log(buf); // Prints: ``` ```cjs const { Buffer } = require('node:buffer'); const buf = Buffer.allocUnsafe(4); buf.writeUInt16BE(0xdead, 0); buf.writeUInt16BE(0xbeef, 2); console.log(buf); // Prints: ``` ### `buf.writeUInt16LE(value[, offset])` \* `value` {integer} Number to be written to `buf`. \* `offset` {integer} Number of bytes to skip before starting to write. Must satisfy `0 <= offset <= buf.length - 2`. \*\*Default:\*\* `0`. \* Returns: {integer} `offset` plus the number of bytes written. Writes `value` to `buf` at the specified `offset` as little-endian. The `value` must be a valid unsigned 16-bit integer. Behavior is undefined when `value` is anything other than an unsigned 16-bit integer. This function is also available under the `writeUint16LE` alias. ```mjs import { Buffer } from 'node:buffer'; const buf = Buffer.allocUnsafe(4); buf.writeUInt16LE(0xdead, 0); buf.writeUInt16LE(0xbeef, 2); console.log(buf); // Prints: ``` ```cjs const { Buffer } = require('node:buffer'); const buf = Buffer.allocUnsafe(4); buf.writeUInt16LE(0xdead, 0); buf.writeUInt16LE(0xbeef, 2); console.log(buf); // Prints: ``` ### `buf.writeUInt32BE(value[, offset])` \* `value` {integer} Number to be written to `buf`. \* `offset` {integer} Number of bytes to skip before starting to write. Must satisfy `0 <= offset <= buf.length - 4`. \*\*Default:\*\* `0`. \* Returns: {integer} `offset` plus the number of bytes written. Writes `value` to `buf` at the specified `offset` as big-endian. The `value` must be a valid unsigned 32-bit integer. Behavior is undefined when `value` is anything other than an unsigned 32-bit integer. This function is also available under the `writeUint32BE` alias. ```mjs import { Buffer } from 'node:buffer'; const buf = Buffer.allocUnsafe(4); buf.writeUInt32BE(0xfeedface, 0); console.log(buf); // Prints: ``` ```cjs const { Buffer } = require('node:buffer'); const buf = Buffer.allocUnsafe(4); buf.writeUInt32BE(0xfeedface, 0); console.log(buf); // Prints: ``` ### `buf.writeUInt32LE(value[, offset])` \* `value` {integer} Number to be written to `buf`. \* `offset` {integer} Number of bytes to skip before starting to write. Must satisfy `0 <= offset <= buf.length - 4`. \*\*Default:\*\* `0`. \* Returns: {integer} `offset` plus the number of bytes written. Writes `value` to `buf` at the specified `offset` as little-endian. The `value` must be a valid unsigned 32-bit integer. Behavior is undefined when `value` is anything other than an unsigned 32-bit integer. This function is also available under the `writeUint32LE` alias. ```mjs import { Buffer } from 'node:buffer'; const buf = Buffer.allocUnsafe(4); buf.writeUInt32LE(0xfeedface, 0); console.log(buf); // Prints: ``` ```cjs const { Buffer } = require('node:buffer'); const buf = Buffer.allocUnsafe(4); buf.writeUInt32LE(0xfeedface, 0); console.log(buf); // Prints: ``` ### `buf.writeUIntBE(value, offset, byteLength)` \* `value` {integer} Number | https://github.com/nodejs/node/blob/main//doc/api/buffer.md | main | nodejs | [
0.05586496368050575,
0.03639595955610275,
-0.022638680413365364,
-0.0015947369392961264,
-0.06608210504055023,
-0.0151588199660182,
0.026136010885238647,
0.08439420908689499,
0.00040997291216626763,
-0.02812778763473034,
-0.04869851469993591,
-0.029386041685938835,
0.009933465160429478,
-0... | 0.063291 |
function is also available under the `writeUint32LE` alias. ```mjs import { Buffer } from 'node:buffer'; const buf = Buffer.allocUnsafe(4); buf.writeUInt32LE(0xfeedface, 0); console.log(buf); // Prints: ``` ```cjs const { Buffer } = require('node:buffer'); const buf = Buffer.allocUnsafe(4); buf.writeUInt32LE(0xfeedface, 0); console.log(buf); // Prints: ``` ### `buf.writeUIntBE(value, offset, byteLength)` \* `value` {integer} Number to be written to `buf`. \* `offset` {integer} Number of bytes to skip before starting to write. Must satisfy `0 <= offset <= buf.length - byteLength`. \* `byteLength` {integer} Number of bytes to write. Must satisfy `0 < byteLength <= 6`. \* Returns: {integer} `offset` plus the number of bytes written. Writes `byteLength` bytes of `value` to `buf` at the specified `offset` as big-endian. Supports up to 48 bits of accuracy. Behavior is undefined when `value` is anything other than an unsigned integer. This function is also available under the `writeUintBE` alias. ```mjs import { Buffer } from 'node:buffer'; const buf = Buffer.allocUnsafe(6); buf.writeUIntBE(0x1234567890ab, 0, 6); console.log(buf); // Prints: ``` ```cjs const { Buffer } = require('node:buffer'); const buf = Buffer.allocUnsafe(6); buf.writeUIntBE(0x1234567890ab, 0, 6); console.log(buf); // Prints: ``` ### `buf.writeUIntLE(value, offset, byteLength)` \* `value` {integer} Number to be written to `buf`. \* `offset` {integer} Number of bytes to skip before starting to write. Must satisfy `0 <= offset <= buf.length - byteLength`. \* `byteLength` {integer} Number of bytes to write. Must satisfy `0 < byteLength <= 6`. \* Returns: {integer} `offset` plus the number of bytes written. Writes `byteLength` bytes of `value` to `buf` at the specified `offset` as little-endian. Supports up to 48 bits of accuracy. Behavior is undefined when `value` is anything other than an unsigned integer. This function is also available under the `writeUintLE` alias. ```mjs import { Buffer } from 'node:buffer'; const buf = Buffer.allocUnsafe(6); buf.writeUIntLE(0x1234567890ab, 0, 6); console.log(buf); // Prints: ``` ```cjs const { Buffer } = require('node:buffer'); const buf = Buffer.allocUnsafe(6); buf.writeUIntLE(0x1234567890ab, 0, 6); console.log(buf); // Prints: ``` ### `new Buffer(array)` > Stability: 0 - Deprecated: Use [`Buffer.from(array)`][] instead. \* `array` {integer\[]} An array of bytes to copy from. See [`Buffer.from(array)`][]. ### `new Buffer(arrayBuffer[, byteOffset[, length]])` > Stability: 0 - Deprecated: Use > [`Buffer.from(arrayBuffer[, byteOffset[, length]])`][`Buffer.from(arrayBuf)`] > instead. \* `arrayBuffer` {ArrayBuffer|SharedArrayBuffer} An {ArrayBuffer}, {SharedArrayBuffer} or the `.buffer` property of a {TypedArray}. \* `byteOffset` {integer} Index of first byte to expose. \*\*Default:\*\* `0`. \* `length` {integer} Number of bytes to expose. \*\*Default:\*\* `arrayBuffer.byteLength - byteOffset`. See [`Buffer.from(arrayBuffer[, byteOffset[, length]])`][`Buffer.from(arrayBuf)`]. ### `new Buffer(buffer)` > Stability: 0 - Deprecated: Use [`Buffer.from(buffer)`][] instead. \* `buffer` {Buffer|Uint8Array} An existing `Buffer` or {Uint8Array} from which to copy data. See [`Buffer.from(buffer)`][]. ### `new Buffer(size)` > Stability: 0 - Deprecated: Use [`Buffer.alloc()`][] instead (also see > [`Buffer.allocUnsafe()`][]). \* `size` {integer} The desired length of the new `Buffer`. See [`Buffer.alloc()`][] and [`Buffer.allocUnsafe()`][]. This variant of the constructor is equivalent to [`Buffer.alloc()`][]. ### `new Buffer(string[, encoding])` > Stability: 0 - Deprecated: > Use [`Buffer.from(string[, encoding])`][`Buffer.from(string)`] instead. \* `string` {string} String to encode. \* `encoding` {string} The encoding of `string`. \*\*Default:\*\* `'utf8'`. See [`Buffer.from(string[, encoding])`][`Buffer.from(string)`]. ## Class: `File` \* Extends: {Blob} A {File} provides information about files. ### `new buffer.File(sources, fileName[, options])` \* `sources` {string\[]|ArrayBuffer\[]|TypedArray\[]|DataView\[]|Blob\[]|File\[]} An array of string, {ArrayBuffer}, {TypedArray}, {DataView}, {File}, or {Blob} objects, or any mix of such objects, that will be stored within the `File`. \* `fileName` {string} The name of the file. \* `options` {Object} \* `endings` {string} One of either `'transparent'` or `'native'`. When set to `'native'`, line endings in string source parts will be converted to the platform native line-ending as specified by `require('node:os').EOL`. \* `type` {string} The File content-type. \* `lastModified` {number} The last modified date of the file. \*\*Default:\*\* `Date.now()`. ### `file.name` \* Type: {string} The | https://github.com/nodejs/node/blob/main//doc/api/buffer.md | main | nodejs | [
0.02459651045501232,
0.0007532120798714459,
-0.03536253422498703,
0.0239572636783123,
-0.05769301578402519,
-0.018931854516267776,
-0.004919396713376045,
0.09276553243398666,
0.004062043968588114,
-0.011674498207867146,
-0.07387685775756836,
-0.026280052959918976,
0.0010262146824970841,
-0... | 0.103841 |
either `'transparent'` or `'native'`. When set to `'native'`, line endings in string source parts will be converted to the platform native line-ending as specified by `require('node:os').EOL`. \* `type` {string} The File content-type. \* `lastModified` {number} The last modified date of the file. \*\*Default:\*\* `Date.now()`. ### `file.name` \* Type: {string} The name of the `File`. ### `file.lastModified` \* Type: {number} The last modified date of the `File`. ## `node:buffer` module APIs While, the `Buffer` object is available as a global, there are additional `Buffer`-related APIs that are available only via the `node:buffer` module accessed using `require('node:buffer')`. ### `buffer.atob(data)` > Stability: 3 - Legacy. Use `Buffer.from(data, 'base64')` instead. \* `data` {any} The Base64-encoded input string. Decodes a string of Base64-encoded data into bytes, and encodes those bytes into a string using Latin-1 (ISO-8859-1). The `data` may be any JavaScript-value that can be coerced into a string. \*\*This function is only provided for compatibility with legacy web platform APIs and should never be used in new code, because they use strings to represent binary data and predate the introduction of typed arrays in JavaScript. For code running using Node.js APIs, converting between base64-encoded strings and binary data should be performed using `Buffer.from(str, 'base64')` and `buf.toString('base64')`.\*\* An automated migration is available ([source](https://github.com/nodejs/userland-migrations/tree/main/recipes/buffer-atob-btoa): ```bash npx codemod@latest @nodejs/buffer-atob-btoa ``` ### `buffer.btoa(data)` > Stability: 3 - Legacy. Use `buf.toString('base64')` instead. \* `data` {any} An ASCII (Latin1) string. Decodes a string into bytes using Latin-1 (ISO-8859), and encodes those bytes into a string using Base64. The `data` may be any JavaScript-value that can be coerced into a string. \*\*This function is only provided for compatibility with legacy web platform APIs and should never be used in new code, because they use strings to represent binary data and predate the introduction of typed arrays in JavaScript. For code running using Node.js APIs, converting between base64-encoded strings and binary data should be performed using `Buffer.from(str, 'base64')` and `buf.toString('base64')`.\*\* An automated migration is available ([source](https://github.com/nodejs/userland-migrations/tree/main/recipes/buffer-atob-btoa): ```bash npx codemod@latest @nodejs/buffer-atob-btoa ``` ### `buffer.isAscii(input)` \* `input` {Buffer | ArrayBuffer | TypedArray} The input to validate. \* Returns: {boolean} This function returns `true` if `input` contains only valid ASCII-encoded data, including the case in which `input` is empty. Throws if the `input` is a detached array buffer. ### `buffer.isUtf8(input)` \* `input` {Buffer | ArrayBuffer | TypedArray} The input to validate. \* Returns: {boolean} This function returns `true` if `input` contains only valid UTF-8-encoded data, including the case in which `input` is empty. Throws if the `input` is a detached array buffer. ### `buffer.INSPECT\_MAX\_BYTES` \* Type: {integer} \*\*Default:\*\* `50` Returns the maximum number of bytes that will be returned when `buf.inspect()` is called. This can be overridden by user modules. See [`util.inspect()`][] for more details on `buf.inspect()` behavior. ### `buffer.kMaxLength` \* Type: {integer} The largest size allowed for a single `Buffer` instance. An alias for [`buffer.constants.MAX\_LENGTH`][]. ### `buffer.kStringMaxLength` \* Type: {integer} The largest length allowed for a single `string` instance. An alias for [`buffer.constants.MAX\_STRING\_LENGTH`][]. ### `buffer.resolveObjectURL(id)` \* `id` {string} A `'blob:nodedata:...` URL string returned by a prior call to `URL.createObjectURL()`. \* Returns: {Blob} Resolves a `'blob:nodedata:...'` an associated {Blob} object registered using a prior call to `URL.createObjectURL()`. ### `buffer.transcode(source, fromEnc, toEnc)` \* `source` {Buffer|Uint8Array} A `Buffer` or `Uint8Array` instance. \* `fromEnc` {string} The current encoding. \* `toEnc` {string} To target encoding. \* Returns: {Buffer} Re-encodes the given `Buffer` or `Uint8Array` instance from one character encoding to another. Returns a new `Buffer` instance. Throws if the `fromEnc` or `toEnc` specify invalid character encodings or if conversion from `fromEnc` to `toEnc` is not permitted. Encodings supported by `buffer.transcode()` are: `'ascii'`, `'utf8'`, `'utf16le'`, `'ucs2'`, `'latin1'`, and `'binary'`. The | https://github.com/nodejs/node/blob/main//doc/api/buffer.md | main | nodejs | [
-0.007816017605364323,
0.042295362800359726,
-0.05388513579964638,
0.01623108983039856,
-0.0027974972035735846,
-0.059292569756507874,
-0.033165156841278076,
0.08141237497329712,
-0.009852539747953415,
0.022207019850611687,
-0.007590955588966608,
-0.0045454534702003,
-0.0806594267487526,
-... | 0.076389 |
the given `Buffer` or `Uint8Array` instance from one character encoding to another. Returns a new `Buffer` instance. Throws if the `fromEnc` or `toEnc` specify invalid character encodings or if conversion from `fromEnc` to `toEnc` is not permitted. Encodings supported by `buffer.transcode()` are: `'ascii'`, `'utf8'`, `'utf16le'`, `'ucs2'`, `'latin1'`, and `'binary'`. The transcoding process will use substitution characters if a given byte sequence cannot be adequately represented in the target encoding. For instance: ```mjs import { Buffer, transcode } from 'node:buffer'; const newBuf = transcode(Buffer.from('€'), 'utf8', 'ascii'); console.log(newBuf.toString('ascii')); // Prints: '?' ``` ```cjs const { Buffer, transcode } = require('node:buffer'); const newBuf = transcode(Buffer.from('€'), 'utf8', 'ascii'); console.log(newBuf.toString('ascii')); // Prints: '?' ``` Because the Euro (`€`) sign is not representable in US-ASCII, it is replaced with `?` in the transcoded `Buffer`. ### Buffer constants #### `buffer.constants.MAX\_LENGTH` \* Type: {integer} The largest size allowed for a single `Buffer` instance. On 32-bit architectures, this value is equal to 231 - 1 (about 2 GiB). On 64-bit architectures, this value is equal to [`Number.MAX\_SAFE\_INTEGER`][] (253 - 1, about 8 PiB). It reflects [`v8::Uint8Array::kMaxLength`][] under the hood. This value is also available as [`buffer.kMaxLength`][]. #### `buffer.constants.MAX\_STRING\_LENGTH` \* Type: {integer} The largest length allowed for a single `string` instance. Represents the largest `length` that a `string` primitive can have, counted in UTF-16 code units. This value may depend on the JS engine that is being used. ## `Buffer.from()`, `Buffer.alloc()`, and `Buffer.allocUnsafe()` In versions of Node.js prior to 6.0.0, `Buffer` instances were created using the `Buffer` constructor function, which allocates the returned `Buffer` differently based on what arguments are provided: \* Passing a number as the first argument to `Buffer()` (e.g. `new Buffer(10)`) allocates a new `Buffer` object of the specified size. Prior to Node.js 8.0.0, the memory allocated for such `Buffer` instances is \_not\_ initialized and \_can contain sensitive data\_. Such `Buffer` instances \_must\_ be subsequently initialized by using either [`buf.fill(0)`][`buf.fill()`] or by writing to the entire `Buffer` before reading data from the `Buffer`. While this behavior is \_intentional\_ to improve performance, development experience has demonstrated that a more explicit distinction is required between creating a fast-but-uninitialized `Buffer` versus creating a slower-but-safer `Buffer`. Since Node.js 8.0.0, `Buffer(num)` and `new Buffer(num)` return a `Buffer` with initialized memory. \* Passing a string, array, or `Buffer` as the first argument copies the passed object's data into the `Buffer`. \* Passing an {ArrayBuffer} or a {SharedArrayBuffer} returns a `Buffer` that shares allocated memory with the given array buffer. Because the behavior of `new Buffer()` is different depending on the type of the first argument, security and reliability issues can be inadvertently introduced into applications when argument validation or `Buffer` initialization is not performed. For example, if an attacker can cause an application to receive a number where a string is expected, the application may call `new Buffer(100)` instead of `new Buffer("100")`, leading it to allocate a 100 byte buffer instead of allocating a 3 byte buffer with content `"100"`. This is commonly possible using JSON API calls. Since JSON distinguishes between numeric and string types, it allows injection of numbers where a naively written application that does not validate its input sufficiently might expect to always receive a string. Before Node.js 8.0.0, the 100 byte buffer might contain arbitrary pre-existing in-memory data, so may be used to expose in-memory secrets to a remote attacker. Since Node.js 8.0.0, exposure of memory cannot occur because the data is zero-filled. However, other attacks are still possible, such as causing very large buffers to be allocated by the server, leading to performance degradation or crashing on memory exhaustion. To make the creation of `Buffer` instances more | https://github.com/nodejs/node/blob/main//doc/api/buffer.md | main | nodejs | [
0.0017675101989880204,
-0.06503736972808838,
-0.0372924841940403,
-0.008038551546633244,
-0.10910660028457642,
-0.019130747765302658,
0.04210398346185684,
0.0287921242415905,
0.010462558828294277,
-0.07718261331319809,
-0.04811764508485794,
-0.04800151661038399,
0.011314029805362225,
0.047... | 0.071307 |
remote attacker. Since Node.js 8.0.0, exposure of memory cannot occur because the data is zero-filled. However, other attacks are still possible, such as causing very large buffers to be allocated by the server, leading to performance degradation or crashing on memory exhaustion. To make the creation of `Buffer` instances more reliable and less error-prone, the various forms of the `new Buffer()` constructor have been \*\*deprecated\*\* and replaced by separate `Buffer.from()`, [`Buffer.alloc()`][], and [`Buffer.allocUnsafe()`][] methods. \_Developers should migrate all existing uses of the `new Buffer()` constructors to one of these new APIs.\_ \* [`Buffer.from(array)`][] returns a new `Buffer` that \_contains a copy\_ of the provided octets. \* [`Buffer.from(arrayBuffer[, byteOffset[, length]])`][`Buffer.from(arrayBuf)`] returns a new `Buffer` that \_shares the same allocated memory\_ as the given {ArrayBuffer}. \* [`Buffer.from(buffer)`][] returns a new `Buffer` that \_contains a copy\_ of the contents of the given `Buffer`. \* [`Buffer.from(string[, encoding])`][`Buffer.from(string)`] returns a new `Buffer` that \_contains a copy\_ of the provided string. \* [`Buffer.alloc(size[, fill[, encoding]])`][`Buffer.alloc()`] returns a new initialized `Buffer` of the specified size. This method is slower than [`Buffer.allocUnsafe(size)`][`Buffer.allocUnsafe()`] but guarantees that newly created `Buffer` instances never contain old data that is potentially sensitive. A `TypeError` will be thrown if `size` is not a number. \* [`Buffer.allocUnsafe(size)`][`Buffer.allocUnsafe()`] and [`Buffer.allocUnsafeSlow(size)`][`Buffer.allocUnsafeSlow()`] each return a new uninitialized `Buffer` of the specified `size`. Because the `Buffer` is uninitialized, the allocated segment of memory might contain old data that is potentially sensitive. `Buffer` instances returned by [`Buffer.allocUnsafe()`][], [`Buffer.from(string)`][], [`Buffer.concat()`][] and [`Buffer.from(array)`][] \_may\_ be allocated off a shared internal memory pool if `size` is less than or equal to half [`Buffer.poolSize`][]. Instances returned by [`Buffer.allocUnsafeSlow()`][] \_never\_ use the shared internal memory pool. ### The `--zero-fill-buffers` command-line option Node.js can be started using the `--zero-fill-buffers` command-line option to cause all newly-allocated `Buffer` instances to be zero-filled upon creation by default. Without the option, buffers created with [`Buffer.allocUnsafe()`][] and [`Buffer.allocUnsafeSlow()`][] are not zero-filled. Use of this flag can have a measurable negative impact on performance. Use the `--zero-fill-buffers` option only when necessary to enforce that newly allocated `Buffer` instances cannot contain old data that is potentially sensitive. ```console $ node --zero-fill-buffers > Buffer.allocUnsafe(5); ``` ### What makes `Buffer.allocUnsafe()` and `Buffer.allocUnsafeSlow()` "unsafe"? When calling [`Buffer.allocUnsafe()`][] and [`Buffer.allocUnsafeSlow()`][], the segment of allocated memory is \_uninitialized\_ (it is not zeroed-out). While this design makes the allocation of memory quite fast, the allocated segment of memory might contain old data that is potentially sensitive. Using a `Buffer` created by [`Buffer.allocUnsafe()`][] without \_completely\_ overwriting the memory can allow this old data to be leaked when the `Buffer` memory is read. While there are clear performance advantages to using [`Buffer.allocUnsafe()`][], extra care \_must\_ be taken in order to avoid introducing security vulnerabilities into an application. [ASCII]: https://en.wikipedia.org/wiki/ASCII [Base64]: https://en.wikipedia.org/wiki/Base64 [ISO-8859-1]: https://en.wikipedia.org/wiki/ISO-8859-1 [RFC 4648, Section 5]: https://tools.ietf.org/html/rfc4648#section-5 [UTF-16]: https://en.wikipedia.org/wiki/UTF-16 [UTF-8]: https://en.wikipedia.org/wiki/UTF-8 [WHATWG Encoding Standard]: https://encoding.spec.whatwg.org/ [`Buffer.alloc()`]: #static-method-bufferallocsize-fill-encoding [`Buffer.allocUnsafe()`]: #static-method-bufferallocunsafesize [`Buffer.allocUnsafeSlow()`]: #static-method-bufferallocunsafeslowsize [`Buffer.concat()`]: #static-method-bufferconcatlist-totallength [`Buffer.copyBytesFrom()`]: #static-method-buffercopybytesfromview-offset-length [`Buffer.from(array)`]: #static-method-bufferfromarray [`Buffer.from(arrayBuf)`]: #static-method-bufferfromarraybuffer-byteoffset-length [`Buffer.from(buffer)`]: #static-method-bufferfrombuffer [`Buffer.from(string)`]: #static-method-bufferfromstring-encoding [`Buffer.poolSize`]: #bufferpoolsize [`ERR\_INVALID\_BUFFER\_SIZE`]: errors.md#err\_invalid\_buffer\_size [`ERR\_OUT\_OF\_RANGE`]: errors.md#err\_out\_of\_range [`JSON.stringify()`]: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global\_Objects/JSON/stringify [`Number.MAX\_SAFE\_INTEGER`]: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global\_Objects/Number/MAX\_SAFE\_INTEGER [`String.prototype.indexOf()`]: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global\_Objects/String/indexOf [`String.prototype.lastIndexOf()`]: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global\_Objects/String/lastIndexOf [`String.prototype.length`]: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global\_Objects/String/length [`TypedArray.from()`]: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global\_Objects/TypedArray/from [`TypedArray.prototype.set()`]: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global\_Objects/TypedArray/set [`TypedArray.prototype.slice()`]: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global\_Objects/TypedArray/slice [`TypedArray.prototype.subarray()`]: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global\_Objects/TypedArray/subarray [`buf.buffer`]: #bufbuffer [`buf.compare()`]: #bufcomparetarget-targetstart-targetend-sourcestart-sourceend [`buf.entries()`]: #bufentries [`buf.fill()`]: #buffillvalue-offset-end-encoding [`buf.indexOf()`]: #bufindexofvalue-byteoffset-encoding [`buf.keys()`]: #bufkeys [`buf.length`]: #buflength [`buf.slice()`]: #bufslicestart-end [`buf.subarray`]: #bufsubarraystart-end [`buf.toString()`]: #buftostringencoding-start-end [`buf.values()`]: #bufvalues [`buffer.constants.MAX\_LENGTH`]: #bufferconstantsmax\_length [`buffer.constants.MAX\_STRING\_LENGTH`]: #bufferconstantsmax\_string\_length [`buffer.kMaxLength`]: #bufferkmaxlength [`util.inspect()`]: util.md#utilinspectobject-options [`v8::Uint8Array::kMaxLength`]: https://v8.github.io/api/head/classv8\_1\_1Uint8Array.html#a7677e3d0c9c92e4d40bef7212f5980c6 [base64url]: https://tools.ietf.org/html/rfc4648#section-5 [endianness]: https://en.wikipedia.org/wiki/Endianness [iterator]: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Iteration\_protocols | https://github.com/nodejs/node/blob/main//doc/api/buffer.md | main | nodejs | [
0.005229267757385969,
0.019473610445857048,
-0.01810527592897415,
0.038212940096855164,
-0.012475375086069107,
-0.04732009768486023,
0.005019794218242168,
0.059956055134534836,
0.018617046996951103,
0.02380765788257122,
-0.04151449352502823,
0.06993476301431656,
-0.03203165531158447,
-0.04... | 0.071506 |
# HTTP > Stability: 2 - Stable This module, containing both a client and server, can be imported via `require('node:http')` (CommonJS) or `import \* as http from 'node:http'` (ES module). The HTTP interfaces in Node.js are designed to support many features of the protocol which have been traditionally difficult to use. In particular, large, possibly chunk-encoded, messages. The interface is careful to never buffer entire requests or responses, so the user is able to stream data. HTTP message headers are represented by an object like this: ```json { "content-length": "123", "content-type": "text/plain", "connection": "keep-alive", "host": "example.com", "accept": "\*/\*" } ``` Keys are lowercased. Values are not modified. In order to support the full spectrum of possible HTTP applications, the Node.js HTTP API is very low-level. It deals with stream handling and message parsing only. It parses a message into headers and body but it does not parse the actual headers or the body. See [`message.headers`][] for details on how duplicate headers are handled. The raw headers as they were received are retained in the `rawHeaders` property, which is an array of `[key, value, key2, value2, ...]`. For example, the previous message header object might have a `rawHeaders` list like the following: ```js [ 'ConTent-Length', '123456', 'content-LENGTH', '123', 'content-type', 'text/plain', 'CONNECTION', 'keep-alive', 'Host', 'example.com', 'accepT', '\*/\*' ] ``` ## Class: `http.Agent` An `Agent` is responsible for managing connection persistence and reuse for HTTP clients. It maintains a queue of pending requests for a given host and port, reusing a single socket connection for each until the queue is empty, at which time the socket is either destroyed or put into a pool where it is kept to be used again for requests to the same host and port. Whether it is destroyed or pooled depends on the `keepAlive` [option](#new-agentoptions). Pooled connections have TCP Keep-Alive enabled for them, but servers may still close idle connections, in which case they will be removed from the pool and a new connection will be made when a new HTTP request is made for that host and port. Servers may also refuse to allow multiple requests over the same connection, in which case the connection will have to be remade for every request and cannot be pooled. The `Agent` will still make the requests to that server, but each one will occur over a new connection. When a connection is closed by the client or the server, it is removed from the pool. Any unused sockets in the pool will be unrefed so as not to keep the Node.js process running when there are no outstanding requests. (see [`socket.unref()`][]). It is good practice, to [`destroy()`][] an `Agent` instance when it is no longer in use, because unused sockets consume OS resources. Sockets are removed from an agent when the socket emits either a `'close'` event or an `'agentRemove'` event. When intending to keep one HTTP request open for a long time without keeping it in the agent, something like the following may be done: ```js http.get(options, (res) => { // Do stuff }).on('socket', (socket) => { socket.emit('agentRemove'); }); ``` An agent may also be used for an individual request. By providing `{agent: false}` as an option to the `http.get()` or `http.request()` functions, a one-time use `Agent` with default options will be used for the client connection. `agent:false`: ```js http.get({ hostname: 'localhost', port: 80, path: '/', agent: false, // Create a new agent just for this one request }, (res) => { // Do stuff with response }); ``` ### `new Agent([options])` \* `options` {Object} Set of configurable options to set on the agent. Can have the | https://github.com/nodejs/node/blob/main//doc/api/http.md | main | nodejs | [
-0.04970283433794975,
0.06934317201375961,
0.02681959606707096,
0.0010236892849206924,
0.030541621148586273,
-0.09825940430164337,
-0.06421869248151779,
0.0010951642179861665,
0.03424397483468056,
0.013715174049139023,
-0.044572461396455765,
0.04068464785814285,
-0.024663709104061127,
-0.0... | 0.153587 |
`agent:false`: ```js http.get({ hostname: 'localhost', port: 80, path: '/', agent: false, // Create a new agent just for this one request }, (res) => { // Do stuff with response }); ``` ### `new Agent([options])` \* `options` {Object} Set of configurable options to set on the agent. Can have the following fields: \* `keepAlive` {boolean} Keep sockets around even when there are no outstanding requests, so they can be used for future requests without having to reestablish a TCP connection. Not to be confused with the `keep-alive` value of the `Connection` header. The `Connection: keep-alive` header is always sent when using an agent except when the `Connection` header is explicitly specified or when the `keepAlive` and `maxSockets` options are respectively set to `false` and `Infinity`, in which case `Connection: close` will be used. \*\*Default:\*\* `false`. \* `keepAliveMsecs` {number} When using the `keepAlive` option, specifies the [initial delay][] for TCP Keep-Alive packets. Ignored when the `keepAlive` option is `false` or `undefined`. \*\*Default:\*\* `1000`. \* `agentKeepAliveTimeoutBuffer` {number} Milliseconds to subtract from the server-provided `keep-alive: timeout=...` hint when determining socket expiration time. This buffer helps ensure the agent closes the socket slightly before the server does, reducing the chance of sending a request on a socket that’s about to be closed by the server. \*\*Default:\*\* `1000`. \* `maxSockets` {number} Maximum number of sockets to allow per host. If the same host opens multiple concurrent connections, each request will use new socket until the `maxSockets` value is reached. If the host attempts to open more connections than `maxSockets`, the additional requests will enter into a pending request queue, and will enter active connection state when an existing connection terminates. This makes sure there are at most `maxSockets` active connections at any point in time, from a given host. \*\*Default:\*\* `Infinity`. \* `maxTotalSockets` {number} Maximum number of sockets allowed for all hosts in total. Each request will use a new socket until the maximum is reached. \*\*Default:\*\* `Infinity`. \* `maxFreeSockets` {number} Maximum number of sockets per host to leave open in a free state. Only relevant if `keepAlive` is set to `true`. \*\*Default:\*\* `256`. \* `scheduling` {string} Scheduling strategy to apply when picking the next free socket to use. It can be `'fifo'` or `'lifo'`. The main difference between the two scheduling strategies is that `'lifo'` selects the most recently used socket, while `'fifo'` selects the least recently used socket. In case of a low rate of request per second, the `'lifo'` scheduling will lower the risk of picking a socket that might have been closed by the server due to inactivity. In case of a high rate of request per second, the `'fifo'` scheduling will maximize the number of open sockets, while the `'lifo'` scheduling will keep it as low as possible. \*\*Default:\*\* `'lifo'`. \* `timeout` {number} Socket timeout in milliseconds. This will set the timeout when the socket is created. \* `proxyEnv` {Object|undefined} Environment variables for proxy configuration. See [Built-in Proxy Support][] for details. \*\*Default:\*\* `undefined` \* `HTTP\_PROXY` {string|undefined} URL for the proxy server that HTTP requests should use. If undefined, no proxy is used for HTTP requests. \* `HTTPS\_PROXY` {string|undefined} URL for the proxy server that HTTPS requests should use. If undefined, no proxy is used for HTTPS requests. \* `NO\_PROXY` {string|undefined} Patterns specifying the endpoints that should not be routed through a proxy. \* `http\_proxy` {string|undefined} Same as `HTTP\_PROXY`. If both are set, `http\_proxy` takes precedence. \* `https\_proxy` {string|undefined} Same as `HTTPS\_PROXY`. If both are set, `https\_proxy` takes precedence. \* `no\_proxy` {string|undefined} Same as `NO\_PROXY`. If both are set, `no\_proxy` takes precedence. \* `defaultPort` {number} Default port to use when the | https://github.com/nodejs/node/blob/main//doc/api/http.md | main | nodejs | [
-0.11515548825263977,
0.04959804564714432,
-0.05662740021944046,
0.040152911096811295,
-0.004501853603869677,
-0.06898890435695648,
-0.017346017062664032,
-0.07672002166509628,
0.015751108527183533,
0.000061017261032247916,
0.0036611363757401705,
0.060508206486701965,
-0.04294667765498161,
... | 0.106133 |
a proxy. \* `http\_proxy` {string|undefined} Same as `HTTP\_PROXY`. If both are set, `http\_proxy` takes precedence. \* `https\_proxy` {string|undefined} Same as `HTTPS\_PROXY`. If both are set, `https\_proxy` takes precedence. \* `no\_proxy` {string|undefined} Same as `NO\_PROXY`. If both are set, `no\_proxy` takes precedence. \* `defaultPort` {number} Default port to use when the port is not specified in requests. \*\*Default:\*\* `80`. \* `protocol` {string} The protocol to use for the agent. \*\*Default:\*\* `'http:'`. `options` in [`socket.connect()`][] are also supported. To configure any of them, a custom [`http.Agent`][] instance must be created. ```mjs import { Agent, request } from 'node:http'; const keepAliveAgent = new Agent({ keepAlive: true }); options.agent = keepAliveAgent; request(options, onResponseCallback); ``` ```cjs const http = require('node:http'); const keepAliveAgent = new http.Agent({ keepAlive: true }); options.agent = keepAliveAgent; http.request(options, onResponseCallback); ``` ### `agent.createConnection(options[, callback])` \* `options` {Object} Options containing connection details. Check [`net.createConnection()`][] for the format of the options. For custom agents, this object is passed to the custom `createConnection` function. \* `callback` {Function} (Optional, primarily for custom agents) A function to be called by a custom `createConnection` implementation when the socket is created, especially for asynchronous operations. \* `err` {Error | null} An error object if socket creation failed. \* `socket` {stream.Duplex} The created socket. \* Returns: {stream.Duplex} The created socket. This is returned by the default implementation or by a custom synchronous `createConnection` implementation. If a custom `createConnection` uses the `callback` for asynchronous operation, this return value might not be the primary way to obtain the socket. Produces a socket/stream to be used for HTTP requests. By default, this function behaves identically to [`net.createConnection()`][], synchronously returning the created socket. The optional `callback` parameter in the signature is \*\*not\*\* used by this default implementation. However, custom agents may override this method to provide greater flexibility, for example, to create sockets asynchronously. When overriding `createConnection`: 1. \*\*Synchronous socket creation\*\*: The overriding method can return the socket/stream directly. 2. \*\*Asynchronous socket creation\*\*: The overriding method can accept the `callback` and pass the created socket/stream to it (e.g., `callback(null, newSocket)`). If an error occurs during socket creation, it should be passed as the first argument to the `callback` (e.g., `callback(err)`). The agent will call the provided `createConnection` function with `options` and this internal `callback`. The `callback` provided by the agent has a signature of `(err, stream)`. ### `agent.keepSocketAlive(socket)` \* `socket` {stream.Duplex} Called when `socket` is detached from a request and could be persisted by the `Agent`. Default behavior is to: ```js socket.setKeepAlive(true, this.keepAliveMsecs); socket.unref(); return true; ``` This method can be overridden by a particular `Agent` subclass. If this method returns a falsy value, the socket will be destroyed instead of persisting it for use with the next request. The `socket` argument can be an instance of {net.Socket}, a subclass of {stream.Duplex}. ### `agent.reuseSocket(socket, request)` \* `socket` {stream.Duplex} \* `request` {http.ClientRequest} Called when `socket` is attached to `request` after being persisted because of the keep-alive options. Default behavior is to: ```js socket.ref(); ``` This method can be overridden by a particular `Agent` subclass. The `socket` argument can be an instance of {net.Socket}, a subclass of {stream.Duplex}. ### `agent.destroy()` Destroy any sockets that are currently in use by the agent. It is usually not necessary to do this. However, if using an agent with `keepAlive` enabled, then it is best to explicitly shut down the agent when it is no longer needed. Otherwise, sockets might stay open for quite a long time before the server terminates them. ### `agent.freeSockets` \* Type: {Object} An object which contains arrays of sockets currently awaiting use by the agent when `keepAlive` is enabled. Do not modify. Sockets in the | https://github.com/nodejs/node/blob/main//doc/api/http.md | main | nodejs | [
-0.05873691663146019,
0.05396053194999695,
-0.037988122552633286,
-0.02067222073674202,
-0.07150011509656906,
-0.06803010404109955,
-0.033752474933862686,
-0.009120091795921326,
-0.016141587868332863,
-0.015537234023213387,
0.0016258034156635404,
0.061599764972925186,
0.004244300536811352,
... | 0.031516 |
agent when it is no longer needed. Otherwise, sockets might stay open for quite a long time before the server terminates them. ### `agent.freeSockets` \* Type: {Object} An object which contains arrays of sockets currently awaiting use by the agent when `keepAlive` is enabled. Do not modify. Sockets in the `freeSockets` list will be automatically destroyed and removed from the array on `'timeout'`. ### `agent.getName([options])` \* `options` {Object} A set of options providing information for name generation \* `host` {string} A domain name or IP address of the server to issue the request to \* `port` {number} Port of remote server \* `localAddress` {string} Local interface to bind for network connections when issuing the request \* `family` {integer} Must be 4 or 6 if this doesn't equal `undefined`. \* Returns: {string} Get a unique name for a set of request options, to determine whether a connection can be reused. For an HTTP agent, this returns `host:port:localAddress` or `host:port:localAddress:family`. For an HTTPS agent, the name includes the CA, cert, ciphers, and other HTTPS/TLS-specific options that determine socket reusability. ### `agent.maxFreeSockets` \* Type: {number} By default set to 256. For agents with `keepAlive` enabled, this sets the maximum number of sockets that will be left open in the free state. ### `agent.maxSockets` \* Type: {number} By default set to `Infinity`. Determines how many concurrent sockets the agent can have open per origin. Origin is the returned value of [`agent.getName()`][]. ### `agent.maxTotalSockets` \* Type: {number} By default set to `Infinity`. Determines how many concurrent sockets the agent can have open. Unlike `maxSockets`, this parameter applies across all origins. ### `agent.requests` \* Type: {Object} An object which contains queues of requests that have not yet been assigned to sockets. Do not modify. ### `agent.sockets` \* Type: {Object} An object which contains arrays of sockets currently in use by the agent. Do not modify. ## Class: `http.ClientRequest` \* Extends: {http.OutgoingMessage} This object is created internally and returned from [`http.request()`][]. It represents an \_in-progress\_ request whose header has already been queued. The header is still mutable using the [`setHeader(name, value)`][], [`getHeader(name)`][], [`removeHeader(name)`][] API. The actual header will be sent along with the first data chunk or when calling [`request.end()`][]. To get the response, add a listener for [`'response'`][] to the request object. [`'response'`][] will be emitted from the request object when the response headers have been received. The [`'response'`][] event is executed with one argument which is an instance of [`http.IncomingMessage`][]. During the [`'response'`][] event, one can add listeners to the response object; particularly to listen for the `'data'` event. If no [`'response'`][] handler is added, then the response will be entirely discarded. However, if a [`'response'`][] event handler is added, then the data from the response object \*\*must\*\* be consumed, either by calling `response.read()` whenever there is a `'readable'` event, or by adding a `'data'` handler, or by calling the `.resume()` method. Until the data is consumed, the `'end'` event will not fire. Also, until the data is read it will consume memory that can eventually lead to a 'process out of memory' error. For backward compatibility, `res` will only emit `'error'` if there is an `'error'` listener registered. Set `Content-Length` header to limit the response body size. If [`response.strictContentLength`][] is set to `true`, mismatching the `Content-Length` header value will result in an `Error` being thrown, identified by `code:` [`'ERR\_HTTP\_CONTENT\_LENGTH\_MISMATCH'`][]. `Content-Length` value should be in bytes, not characters. Use [`Buffer.byteLength()`][] to determine the length of the body in bytes. ### Event: `'abort'` > Stability: 0 - Deprecated. Listen for the `'close'` event instead. Emitted when the request has been aborted by the client. This event | https://github.com/nodejs/node/blob/main//doc/api/http.md | main | nodejs | [
-0.07282788306474686,
0.011057127267122269,
-0.07263530045747757,
0.03687566891312599,
-0.011517076753079891,
-0.037038881331682205,
-0.012114890851080418,
-0.07758446037769318,
0.05691729113459587,
0.003788500325754285,
0.013626315630972385,
0.05673656240105629,
-0.018452320247888565,
-0.... | 0.127766 |
thrown, identified by `code:` [`'ERR\_HTTP\_CONTENT\_LENGTH\_MISMATCH'`][]. `Content-Length` value should be in bytes, not characters. Use [`Buffer.byteLength()`][] to determine the length of the body in bytes. ### Event: `'abort'` > Stability: 0 - Deprecated. Listen for the `'close'` event instead. Emitted when the request has been aborted by the client. This event is only emitted on the first call to `abort()`. ### Event: `'close'` Indicates that the request is completed, or its underlying connection was terminated prematurely (before the response completion). ### Event: `'connect'` \* `response` {http.IncomingMessage} \* `socket` {stream.Duplex} \* `head` {Buffer} Emitted each time a server responds to a request with a `CONNECT` method. If this event is not being listened for, clients receiving a `CONNECT` method will have their connections closed. This event is guaranteed to be passed an instance of the {net.Socket} class, a subclass of {stream.Duplex}, unless the user specifies a socket type other than {net.Socket}. A client and server pair demonstrating how to listen for the `'connect'` event: ```mjs import { createServer, request } from 'node:http'; import { connect } from 'node:net'; import { URL } from 'node:url'; // Create an HTTP tunneling proxy const proxy = createServer((req, res) => { res.writeHead(200, { 'Content-Type': 'text/plain' }); res.end('okay'); }); proxy.on('connect', (req, clientSocket, head) => { // Connect to an origin server const { port, hostname } = new URL(`http://${req.url}`); const serverSocket = connect(port || 80, hostname, () => { clientSocket.write('HTTP/1.1 200 Connection Established\r\n' + 'Proxy-agent: Node.js-Proxy\r\n' + '\r\n'); serverSocket.write(head); serverSocket.pipe(clientSocket); clientSocket.pipe(serverSocket); }); }); // Now that proxy is running proxy.listen(1337, '127.0.0.1', () => { // Make a request to a tunneling proxy const options = { port: 1337, host: '127.0.0.1', method: 'CONNECT', path: 'www.google.com:80', }; const req = request(options); req.end(); req.on('connect', (res, socket, head) => { console.log('got connected!'); // Make a request over an HTTP tunnel socket.write('GET / HTTP/1.1\r\n' + 'Host: www.google.com:80\r\n' + 'Connection: close\r\n' + '\r\n'); socket.on('data', (chunk) => { console.log(chunk.toString()); }); socket.on('end', () => { proxy.close(); }); }); }); ``` ```cjs const http = require('node:http'); const net = require('node:net'); const { URL } = require('node:url'); // Create an HTTP tunneling proxy const proxy = http.createServer((req, res) => { res.writeHead(200, { 'Content-Type': 'text/plain' }); res.end('okay'); }); proxy.on('connect', (req, clientSocket, head) => { // Connect to an origin server const { port, hostname } = new URL(`http://${req.url}`); const serverSocket = net.connect(port || 80, hostname, () => { clientSocket.write('HTTP/1.1 200 Connection Established\r\n' + 'Proxy-agent: Node.js-Proxy\r\n' + '\r\n'); serverSocket.write(head); serverSocket.pipe(clientSocket); clientSocket.pipe(serverSocket); }); }); // Now that proxy is running proxy.listen(1337, '127.0.0.1', () => { // Make a request to a tunneling proxy const options = { port: 1337, host: '127.0.0.1', method: 'CONNECT', path: 'www.google.com:80', }; const req = http.request(options); req.end(); req.on('connect', (res, socket, head) => { console.log('got connected!'); // Make a request over an HTTP tunnel socket.write('GET / HTTP/1.1\r\n' + 'Host: www.google.com:80\r\n' + 'Connection: close\r\n' + '\r\n'); socket.on('data', (chunk) => { console.log(chunk.toString()); }); socket.on('end', () => { proxy.close(); }); }); }); ``` ### Event: `'continue'` Emitted when the server sends a '100 Continue' HTTP response, usually because the request contained 'Expect: 100-continue'. This is an instruction that the client should send the request body. ### Event: `'finish'` Emitted when the request has been sent. More specifically, this event is emitted when the last segment of the request headers and body have been handed off to the operating system for transmission over the network. It does not imply that the server has received anything yet. ### Event: `'information'` \* `info` {Object} \* `httpVersion` {string} \* `httpVersionMajor` {integer} \* `httpVersionMinor` {integer} \* `statusCode` {integer} \* `statusMessage` {string} \* `headers` {Object} \* `rawHeaders` {string\[]} Emitted when the server sends a 1xx intermediate | https://github.com/nodejs/node/blob/main//doc/api/http.md | main | nodejs | [
-0.0493033267557621,
0.033049844205379486,
0.0019479437032714486,
0.007647703401744366,
-0.02228691801428795,
-0.11655990779399872,
0.023279840126633644,
0.009152643382549286,
0.05028251186013222,
0.01509373914450407,
-0.018396621569991112,
0.04664439707994461,
-0.0040617333725094795,
-0.0... | 0.098404 |
transmission over the network. It does not imply that the server has received anything yet. ### Event: `'information'` \* `info` {Object} \* `httpVersion` {string} \* `httpVersionMajor` {integer} \* `httpVersionMinor` {integer} \* `statusCode` {integer} \* `statusMessage` {string} \* `headers` {Object} \* `rawHeaders` {string\[]} Emitted when the server sends a 1xx intermediate response (excluding 101 Upgrade). The listeners of this event will receive an object containing the HTTP version, status code, status message, key-value headers object, and array with the raw header names followed by their respective values. ```mjs import { request } from 'node:http'; const options = { host: '127.0.0.1', port: 8080, path: '/length\_request', }; // Make a request const req = request(options); req.end(); req.on('information', (info) => { console.log(`Got information prior to main response: ${info.statusCode}`); }); ``` ```cjs const http = require('node:http'); const options = { host: '127.0.0.1', port: 8080, path: '/length\_request', }; // Make a request const req = http.request(options); req.end(); req.on('information', (info) => { console.log(`Got information prior to main response: ${info.statusCode}`); }); ``` 101 Upgrade statuses do not fire this event due to their break from the traditional HTTP request/response chain, such as web sockets, in-place TLS upgrades, or HTTP 2.0. To be notified of 101 Upgrade notices, listen for the [`'upgrade'`][] event instead. ### Event: `'response'` \* `response` {http.IncomingMessage} Emitted when a response is received to this request. This event is emitted only once. ### Event: `'socket'` \* `socket` {stream.Duplex} This event is guaranteed to be passed an instance of the {net.Socket} class, a subclass of {stream.Duplex}, unless the user specifies a socket type other than {net.Socket}. ### Event: `'timeout'` Emitted when the underlying socket times out from inactivity. This only notifies that the socket has been idle. The request must be destroyed manually. See also: [`request.setTimeout()`][]. ### Event: `'upgrade'` \* `response` {http.IncomingMessage} \* `stream` {stream.Duplex} \* `head` {Buffer} Emitted each time a server responds to a request with an upgrade. If this event is not being listened for and the response status code is 101 Switching Protocols, clients receiving an upgrade header will have their connections closed. This event is guaranteed to be passed an instance of the {net.Socket} class, a subclass of {stream.Duplex}, unless the user specifies a socket type other than {net.Socket}. A client server pair demonstrating how to listen for the `'upgrade'` event. ```mjs import http from 'node:http'; import process from 'node:process'; // Create an HTTP server const server = http.createServer((req, res) => { res.writeHead(200, { 'Content-Type': 'text/plain' }); res.end('okay'); }); server.on('upgrade', (req, stream, head) => { stream.write('HTTP/1.1 101 Web Socket Protocol Handshake\r\n' + 'Upgrade: WebSocket\r\n' + 'Connection: Upgrade\r\n' + '\r\n'); stream.pipe(stream); // echo back }); // Now that server is running server.listen(1337, '127.0.0.1', () => { // make a request const options = { port: 1337, host: '127.0.0.1', headers: { 'Connection': 'Upgrade', 'Upgrade': 'websocket', }, }; const req = http.request(options); req.end(); req.on('upgrade', (res, stream, upgradeHead) => { console.log('got upgraded!'); stream.end(); process.exit(0); }); }); ``` ```cjs const http = require('node:http'); // Create an HTTP server const server = http.createServer((req, res) => { res.writeHead(200, { 'Content-Type': 'text/plain' }); res.end('okay'); }); server.on('upgrade', (req, stream, head) => { stream.write('HTTP/1.1 101 Web Socket Protocol Handshake\r\n' + 'Upgrade: WebSocket\r\n' + 'Connection: Upgrade\r\n' + '\r\n'); stream.pipe(stream); // echo back }); // Now that server is running server.listen(1337, '127.0.0.1', () => { // make a request const options = { port: 1337, host: '127.0.0.1', headers: { 'Connection': 'Upgrade', 'Upgrade': 'websocket', }, }; const req = http.request(options); req.end(); req.on('upgrade', (res, stream, upgradeHead) => { console.log('got upgraded!'); stream.end(); process.exit(0); }); }); ``` ### `request.abort()` > Stability: 0 - Deprecated: Use [`request.destroy()`][] instead. Marks the request as aborting. Calling this will cause remaining data | https://github.com/nodejs/node/blob/main//doc/api/http.md | main | nodejs | [
-0.010613144375383854,
0.11017804592847824,
0.04822598770260811,
0.014274084009230137,
0.03787943348288536,
-0.08748658746480942,
-0.01311260275542736,
-0.028382964432239532,
0.07400552928447723,
0.04069969058036804,
-0.017366943880915642,
0.009417190216481686,
0.004391341470181942,
-0.023... | 0.073943 |
1337, host: '127.0.0.1', headers: { 'Connection': 'Upgrade', 'Upgrade': 'websocket', }, }; const req = http.request(options); req.end(); req.on('upgrade', (res, stream, upgradeHead) => { console.log('got upgraded!'); stream.end(); process.exit(0); }); }); ``` ### `request.abort()` > Stability: 0 - Deprecated: Use [`request.destroy()`][] instead. Marks the request as aborting. Calling this will cause remaining data in the response to be dropped and the socket to be destroyed. ### `request.aborted` > Stability: 0 - Deprecated. Check [`request.destroyed`][] instead. \* Type: {boolean} The `request.aborted` property will be `true` if the request has been aborted. ### `request.connection` > Stability: 0 - Deprecated. Use [`request.socket`][]. \* Type: {stream.Duplex} See [`request.socket`][]. ### `request.cork()` See [`writable.cork()`][]. ### `request.end([data[, encoding]][, callback])` \* `data` {string|Buffer|Uint8Array} \* `encoding` {string} \* `callback` {Function} \* Returns: {this} Finishes sending the request. If any parts of the body are unsent, it will flush them to the stream. If the request is chunked, this will send the terminating `'0\r\n\r\n'`. If `data` is specified, it is equivalent to calling [`request.write(data, encoding)`][] followed by `request.end(callback)`. If `callback` is specified, it will be called when the request stream is finished. ### `request.destroy([error])` \* `error` {Error} Optional, an error to emit with `'error'` event. \* Returns: {this} Destroy the request. Optionally emit an `'error'` event, and emit a `'close'` event. Calling this will cause remaining data in the response to be dropped and the socket to be destroyed. See [`writable.destroy()`][] for further details. #### `request.destroyed` \* Type: {boolean} Is `true` after [`request.destroy()`][] has been called. See [`writable.destroyed`][] for further details. ### `request.finished` > Stability: 0 - Deprecated. Use [`request.writableEnded`][]. \* Type: {boolean} The `request.finished` property will be `true` if [`request.end()`][] has been called. `request.end()` will automatically be called if the request was initiated via [`http.get()`][]. ### `request.flushHeaders()` Flushes the request headers. For efficiency reasons, Node.js normally buffers the request headers until `request.end()` is called or the first chunk of request data is written. It then tries to pack the request headers and data into a single TCP packet. That's usually desired (it saves a TCP round-trip), but not when the first data is not sent until possibly much later. `request.flushHeaders()` bypasses the optimization and kickstarts the request. ### `request.getHeader(name)` \* `name` {string} \* Returns: {any} Reads out a header on the request. The name is case-insensitive. The type of the return value depends on the arguments provided to [`request.setHeader()`][]. ```js request.setHeader('content-type', 'text/html'); request.setHeader('Content-Length', Buffer.byteLength(body)); request.setHeader('Cookie', ['type=ninja', 'language=javascript']); const contentType = request.getHeader('Content-Type'); // 'contentType' is 'text/html' const contentLength = request.getHeader('Content-Length'); // 'contentLength' is of type number const cookie = request.getHeader('Cookie'); // 'cookie' is of type string[] ``` ### `request.getHeaderNames()` \* Returns: {string\[]} Returns an array containing the unique names of the current outgoing headers. All header names are lowercase. ```js request.setHeader('Foo', 'bar'); request.setHeader('Cookie', ['foo=bar', 'bar=baz']); const headerNames = request.getHeaderNames(); // headerNames === ['foo', 'cookie'] ``` ### `request.getHeaders()` \* Returns: {Object} Returns a shallow copy of the current outgoing headers. Since a shallow copy is used, array values may be mutated without additional calls to various header-related http module methods. The keys of the returned object are the header names and the values are the respective header values. All header names are lowercase. The object returned by the `request.getHeaders()` method \_does not\_ prototypically inherit from the JavaScript `Object`. This means that typical `Object` methods such as `obj.toString()`, `obj.hasOwnProperty()`, and others are not defined and \_will not work\_. ```js request.setHeader('Foo', 'bar'); request.setHeader('Cookie', ['foo=bar', 'bar=baz']); const headers = request.getHeaders(); // headers === { foo: 'bar', 'cookie': ['foo=bar', 'bar=baz'] } ``` ### `request.getRawHeaderNames()` \* Returns: {string\[]} Returns an array containing the unique names of the current outgoing raw headers. Header names are returned with their exact casing | https://github.com/nodejs/node/blob/main//doc/api/http.md | main | nodejs | [
-0.07332562655210495,
0.07402986288070679,
-0.004611031152307987,
-0.002926026936620474,
0.00008529706974513829,
-0.08352895081043243,
-0.06544134765863419,
0.014465205371379852,
-0.004628104157745838,
-0.013857312500476837,
-0.04281154274940491,
0.06387650221586227,
-0.06370903551578522,
... | 0.061611 |
\_will not work\_. ```js request.setHeader('Foo', 'bar'); request.setHeader('Cookie', ['foo=bar', 'bar=baz']); const headers = request.getHeaders(); // headers === { foo: 'bar', 'cookie': ['foo=bar', 'bar=baz'] } ``` ### `request.getRawHeaderNames()` \* Returns: {string\[]} Returns an array containing the unique names of the current outgoing raw headers. Header names are returned with their exact casing being set. ```js request.setHeader('Foo', 'bar'); request.setHeader('Set-Cookie', ['foo=bar', 'bar=baz']); const headerNames = request.getRawHeaderNames(); // headerNames === ['Foo', 'Set-Cookie'] ``` ### `request.hasHeader(name)` \* `name` {string} \* Returns: {boolean} Returns `true` if the header identified by `name` is currently set in the outgoing headers. The header name matching is case-insensitive. ```js const hasContentType = request.hasHeader('content-type'); ``` ### `request.maxHeadersCount` \* Type: {number} \*\*Default:\*\* `2000` Limits maximum response headers count. If set to 0, no limit will be applied. ### `request.path` \* Type: {string} The request path. ### `request.method` \* Type: {string} The request method. ### `request.host` \* Type: {string} The request host. ### `request.protocol` \* Type: {string} The request protocol. ### `request.removeHeader(name)` \* `name` {string} Removes a header that's already defined into headers object. ```js request.removeHeader('Content-Type'); ``` ### `request.reusedSocket` \* Type: {boolean} Whether the request is send through a reused socket. When sending request through a keep-alive enabled agent, the underlying socket might be reused. But if server closes connection at unfortunate time, client may run into a 'ECONNRESET' error. ```mjs import http from 'node:http'; const agent = new http.Agent({ keepAlive: true }); // Server has a 5 seconds keep-alive timeout by default http .createServer((req, res) => { res.write('hello\n'); res.end(); }) .listen(3000); setInterval(() => { // Adapting a keep-alive agent http.get('http://localhost:3000', { agent }, (res) => { res.on('data', (data) => { // Do nothing }); }); }, 5000); // Sending request on 5s interval so it's easy to hit idle timeout ``` ```cjs const http = require('node:http'); const agent = new http.Agent({ keepAlive: true }); // Server has a 5 seconds keep-alive timeout by default http .createServer((req, res) => { res.write('hello\n'); res.end(); }) .listen(3000); setInterval(() => { // Adapting a keep-alive agent http.get('http://localhost:3000', { agent }, (res) => { res.on('data', (data) => { // Do nothing }); }); }, 5000); // Sending request on 5s interval so it's easy to hit idle timeout ``` By marking a request whether it reused socket or not, we can do automatic error retry base on it. ```mjs import http from 'node:http'; const agent = new http.Agent({ keepAlive: true }); function retriableRequest() { const req = http .get('http://localhost:3000', { agent }, (res) => { // ... }) .on('error', (err) => { // Check if retry is needed if (req.reusedSocket && err.code === 'ECONNRESET') { retriableRequest(); } }); } retriableRequest(); ``` ```cjs const http = require('node:http'); const agent = new http.Agent({ keepAlive: true }); function retriableRequest() { const req = http .get('http://localhost:3000', { agent }, (res) => { // ... }) .on('error', (err) => { // Check if retry is needed if (req.reusedSocket && err.code === 'ECONNRESET') { retriableRequest(); } }); } retriableRequest(); ``` ### `request.setHeader(name, value)` \* `name` {string} \* `value` {any} Sets a single header value for headers object. If this header already exists in the to-be-sent headers, its value will be replaced. Use an array of strings here to send multiple headers with the same name. Non-string values will be stored without modification. Therefore, [`request.getHeader()`][] may return non-string values. However, the non-string values will be converted to strings for network transmission. ```js request.setHeader('Content-Type', 'application/json'); ``` or ```js request.setHeader('Cookie', ['type=ninja', 'language=javascript']); ``` When the value is a string an exception will be thrown if it contains characters outside the `latin1` encoding. If you need to pass UTF-8 characters in the value please encode the value using the | https://github.com/nodejs/node/blob/main//doc/api/http.md | main | nodejs | [
-0.11407145857810974,
0.07207569479942322,
0.0199221670627594,
-0.03983641788363457,
-0.02373097650706768,
-0.05539395287632942,
0.06122642382979393,
0.020452601835131645,
0.017138298600912094,
-0.047588687390089035,
-0.058049727231264114,
-0.050800543278455734,
-0.01885862834751606,
0.000... | -0.023289 |
to strings for network transmission. ```js request.setHeader('Content-Type', 'application/json'); ``` or ```js request.setHeader('Cookie', ['type=ninja', 'language=javascript']); ``` When the value is a string an exception will be thrown if it contains characters outside the `latin1` encoding. If you need to pass UTF-8 characters in the value please encode the value using the [RFC 8187][] standard. ```js const filename = 'Rock 🎵.txt'; request.setHeader('Content-Disposition', `attachment; filename\*=utf-8''${encodeURIComponent(filename)}`); ``` ### `request.setNoDelay([noDelay])` \* `noDelay` {boolean} Once a socket is assigned to this request and is connected [`socket.setNoDelay()`][] will be called. ### `request.setSocketKeepAlive([enable][, initialDelay])` \* `enable` {boolean} \* `initialDelay` {number} Once a socket is assigned to this request and is connected [`socket.setKeepAlive()`][] will be called. ### `request.setTimeout(timeout[, callback])` \* `timeout` {number} Milliseconds before a request times out. \* `callback` {Function} Optional function to be called when a timeout occurs. Same as binding to the `'timeout'` event. \* Returns: {http.ClientRequest} Once a socket is assigned to this request and is connected [`socket.setTimeout()`][] will be called. ### `request.socket` \* Type: {stream.Duplex} Reference to the underlying socket. Usually users will not want to access this property. In particular, the socket will not emit `'readable'` events because of how the protocol parser attaches to the socket. ```mjs import http from 'node:http'; const options = { host: 'www.google.com', }; const req = http.get(options); req.end(); req.once('response', (res) => { const ip = req.socket.localAddress; const port = req.socket.localPort; console.log(`Your IP address is ${ip} and your source port is ${port}.`); // Consume response object }); ``` ```cjs const http = require('node:http'); const options = { host: 'www.google.com', }; const req = http.get(options); req.end(); req.once('response', (res) => { const ip = req.socket.localAddress; const port = req.socket.localPort; console.log(`Your IP address is ${ip} and your source port is ${port}.`); // Consume response object }); ``` This property is guaranteed to be an instance of the {net.Socket} class, a subclass of {stream.Duplex}, unless the user specified a socket type other than {net.Socket}. ### `request.uncork()` See [`writable.uncork()`][]. ### `request.writableEnded` \* Type: {boolean} Is `true` after [`request.end()`][] has been called. This property does not indicate whether the data has been flushed, for this use [`request.writableFinished`][] instead. ### `request.writableFinished` \* Type: {boolean} Is `true` if all data has been flushed to the underlying system, immediately before the [`'finish'`][] event is emitted. ### `request.write(chunk[, encoding][, callback])` \* `chunk` {string|Buffer|Uint8Array} \* `encoding` {string} \* `callback` {Function} \* Returns: {boolean} Sends a chunk of the body. This method can be called multiple times. If no `Content-Length` is set, data will automatically be encoded in HTTP Chunked transfer encoding, so that server knows when the data ends. The `Transfer-Encoding: chunked` header is added. Calling [`request.end()`][] is necessary to finish sending the request. The `encoding` argument is optional and only applies when `chunk` is a string. Defaults to `'utf8'`. The `callback` argument is optional and will be called when this chunk of data is flushed, but only if the chunk is non-empty. Returns `true` if the entire data was flushed successfully to the kernel buffer. Returns `false` if all or part of the data was queued in user memory. `'drain'` will be emitted when the buffer is free again. When `write` function is called with empty string or buffer, it does nothing and waits for more input. ## Class: `http.Server` \* Extends: {net.Server} ### Event: `'checkContinue'` \* `request` {http.IncomingMessage} \* `response` {http.ServerResponse} Emitted each time a request with an HTTP `Expect: 100-continue` is received. If this event is not listened for, the server will automatically respond with a `100 Continue` as appropriate. Handling this event involves calling [`response.writeContinue()`][] if the client should continue to send the request body, or generating an appropriate HTTP response (e.g. 400 Bad Request) | https://github.com/nodejs/node/blob/main//doc/api/http.md | main | nodejs | [
-0.010936086997389793,
0.028203854337334633,
-0.032903242856264114,
-0.01802241802215576,
-0.0584852360188961,
-0.003434751182794571,
0.05012810602784157,
0.05274142697453499,
0.032649267464876175,
-0.044054705649614334,
-0.045945215970277786,
-0.010434734635055065,
-0.0008083685534074903,
... | 0.040676 |
an HTTP `Expect: 100-continue` is received. If this event is not listened for, the server will automatically respond with a `100 Continue` as appropriate. Handling this event involves calling [`response.writeContinue()`][] if the client should continue to send the request body, or generating an appropriate HTTP response (e.g. 400 Bad Request) if the client should not continue to send the request body. When this event is emitted and handled, the [`'request'`][] event will not be emitted. ### Event: `'checkExpectation'` \* `request` {http.IncomingMessage} \* `response` {http.ServerResponse} Emitted each time a request with an HTTP `Expect` header is received, where the value is not `100-continue`. If this event is not listened for, the server will automatically respond with a `417 Expectation Failed` as appropriate. When this event is emitted and handled, the [`'request'`][] event will not be emitted. ### Event: `'clientError'` \* `exception` {Error} \* `socket` {stream.Duplex} If a client connection emits an `'error'` event, it will be forwarded here. Listener of this event is responsible for closing/destroying the underlying socket. For example, one may wish to more gracefully close the socket with a custom HTTP response instead of abruptly severing the connection. The socket \*\*must be closed or destroyed\*\* before the listener ends. This event is guaranteed to be passed an instance of the {net.Socket} class, a subclass of {stream.Duplex}, unless the user specifies a socket type other than {net.Socket}. Default behavior is to try close the socket with a HTTP '400 Bad Request', or a HTTP '431 Request Header Fields Too Large' in the case of a [`HPE\_HEADER\_OVERFLOW`][] error. If the socket is not writable or headers of the current attached [`http.ServerResponse`][] has been sent, it is immediately destroyed. `socket` is the [`net.Socket`][] object that the error originated from. ```mjs import http from 'node:http'; const server = http.createServer((req, res) => { res.end(); }); server.on('clientError', (err, socket) => { socket.end('HTTP/1.1 400 Bad Request\r\n\r\n'); }); server.listen(8000); ``` ```cjs const http = require('node:http'); const server = http.createServer((req, res) => { res.end(); }); server.on('clientError', (err, socket) => { socket.end('HTTP/1.1 400 Bad Request\r\n\r\n'); }); server.listen(8000); ``` When the `'clientError'` event occurs, there is no `request` or `response` object, so any HTTP response sent, including response headers and payload, \_must\_ be written directly to the `socket` object. Care must be taken to ensure the response is a properly formatted HTTP response message. `err` is an instance of `Error` with two extra columns: \* `bytesParsed`: the bytes count of request packet that Node.js may have parsed correctly; \* `rawPacket`: the raw packet of current request. In some cases, the client has already received the response and/or the socket has already been destroyed, like in case of `ECONNRESET` errors. Before trying to send data to the socket, it is better to check that it is still writable. ```js server.on('clientError', (err, socket) => { if (err.code === 'ECONNRESET' || !socket.writable) { return; } socket.end('HTTP/1.1 400 Bad Request\r\n\r\n'); }); ``` ### Event: `'close'` Emitted when the server closes. ### Event: `'connect'` \* `request` {http.IncomingMessage} Arguments for the HTTP request, as it is in the [`'request'`][] event \* `socket` {stream.Duplex} Network socket between the server and client \* `head` {Buffer} The first packet of the tunneling stream (may be empty) Emitted each time a client requests an HTTP `CONNECT` method. If this event is not listened for, then clients requesting a `CONNECT` method will have their connections closed. This event is guaranteed to be passed an instance of the {net.Socket} class, a subclass of {stream.Duplex}, unless the user specifies a socket type other than {net.Socket}. After this event is emitted, the request's socket will not have a `'data'` event listener, meaning it | https://github.com/nodejs/node/blob/main//doc/api/http.md | main | nodejs | [
-0.07145173102617264,
0.03524671494960785,
0.016143186017870903,
0.020796187222003937,
-0.02385338395833969,
-0.12266597896814346,
0.008140827529132366,
-0.015033505856990814,
0.07038015872240067,
0.05785829946398735,
-0.031148472800850868,
0.013639162294566631,
0.023627083748579025,
0.032... | 0.099074 |
method will have their connections closed. This event is guaranteed to be passed an instance of the {net.Socket} class, a subclass of {stream.Duplex}, unless the user specifies a socket type other than {net.Socket}. After this event is emitted, the request's socket will not have a `'data'` event listener, meaning it will need to be bound in order to handle data sent to the server on that socket. ### Event: `'connection'` \* `socket` {stream.Duplex} This event is emitted when a new TCP stream is established. `socket` is typically an object of type [`net.Socket`][]. Usually users will not want to access this event. In particular, the socket will not emit `'readable'` events because of how the protocol parser attaches to the socket. The `socket` can also be accessed at `request.socket`. This event can also be explicitly emitted by users to inject connections into the HTTP server. In that case, any [`Duplex`][] stream can be passed. If `socket.setTimeout()` is called here, the timeout will be replaced with `server.keepAliveTimeout` when the socket has served a request (if `server.keepAliveTimeout` is non-zero). This event is guaranteed to be passed an instance of the {net.Socket} class, a subclass of {stream.Duplex}, unless the user specifies a socket type other than {net.Socket}. ### Event: `'dropRequest'` \* `request` {http.IncomingMessage} Arguments for the HTTP request, as it is in the [`'request'`][] event \* `socket` {stream.Duplex} Network socket between the server and client When the number of requests on a socket reaches the threshold of `server.maxRequestsPerSocket`, the server will drop new requests and emit `'dropRequest'` event instead, then send `503` to client. ### Event: `'request'` \* `request` {http.IncomingMessage} \* `response` {http.ServerResponse} Emitted each time there is a request. There may be multiple requests per connection (in the case of HTTP Keep-Alive connections). ### Event: `'upgrade'` \* `request` {http.IncomingMessage} Arguments for the HTTP request, as it is in the [`'request'`][] event \* `stream` {stream.Duplex} The upgraded stream between the server and client \* `head` {Buffer} The first packet of the upgraded stream (may be empty) Emitted each time a client's HTTP upgrade request is accepted. By default all HTTP upgrade requests are ignored (i.e. only regular `'request'` events are emitted, sticking with the normal HTTP request/response flow) unless you listen to this event, in which case they are all accepted (i.e. the `'upgrade'` event is emitted instead, and future communication must handled directly through the raw stream). You can control this more precisely by using the server `shouldUpgradeCallback` option. Listening to this event is optional and clients cannot insist on a protocol change. If an upgrade is accepted by `shouldUpgradeCallback` but no event handler is registered then the socket will be destroyed, resulting in an immediate connection closure for the client. In the uncommon case that the incoming request has a body, this body will be parsed as normal, separate to the upgrade stream, and the raw stream data will only begin after it has completed. To ensure that reading from the stream isn't blocked by waiting for the request body to be read, any reads on the stream will start the request body flowing automatically. If you want to read the request body, ensure that you do so (i.e. you attach `'data'` listeners) before starting to read from the upgraded stream. The stream argument will typically be the {net.Socket} instance used by the request, but in some cases (such as with a request body) it may be a duplex stream. If required, you can access the raw connection underlying the request via [`request.socket`][], which is guaranteed to be an instance of {net.Socket} unless the user specified another socket type. ### `server.close([callback])` \* | https://github.com/nodejs/node/blob/main//doc/api/http.md | main | nodejs | [
-0.07979297637939453,
0.03066437691450119,
-0.029123853892087936,
0.02942594699561596,
-0.0589771643280983,
-0.03743715584278107,
0.04474511370062828,
0.00396703789010644,
0.06332509964704514,
0.0017563675064593554,
-0.004966932814568281,
0.10175907611846924,
-0.03534667193889618,
-0.01414... | 0.132778 |
the request, but in some cases (such as with a request body) it may be a duplex stream. If required, you can access the raw connection underlying the request via [`request.socket`][], which is guaranteed to be an instance of {net.Socket} unless the user specified another socket type. ### `server.close([callback])` \* `callback` {Function} Stops the server from accepting new connections and closes all connections connected to this server which are not sending a request or waiting for a response. See [`net.Server.close()`][]. ```js const http = require('node:http'); const server = http.createServer({ keepAliveTimeout: 60000 }, (req, res) => { res.writeHead(200, { 'Content-Type': 'application/json' }); res.end(JSON.stringify({ data: 'Hello World!', })); }); server.listen(8000); // Close the server after 10 seconds setTimeout(() => { server.close(() => { console.log('server on port 8000 closed successfully'); }); }, 10000); ``` ### `server.closeAllConnections()` Closes all established HTTP(S) connections connected to this server, including active connections connected to this server which are sending a request or waiting for a response. This does \_not\_ destroy sockets upgraded to a different protocol, such as WebSocket or HTTP/2. > This is a forceful way of closing all connections and should be used with > caution. Whenever using this in conjunction with `server.close`, calling this > \_after\_ `server.close` is recommended as to avoid race conditions where new > connections are created between a call to this and a call to `server.close`. ```js const http = require('node:http'); const server = http.createServer({ keepAliveTimeout: 60000 }, (req, res) => { res.writeHead(200, { 'Content-Type': 'application/json' }); res.end(JSON.stringify({ data: 'Hello World!', })); }); server.listen(8000); // Close the server after 10 seconds setTimeout(() => { server.close(() => { console.log('server on port 8000 closed successfully'); }); // Closes all connections, ensuring the server closes successfully server.closeAllConnections(); }, 10000); ``` ### `server.closeIdleConnections()` Closes all connections connected to this server which are not sending a request or waiting for a response. > Starting with Node.js 19.0.0, there's no need for calling this method in > conjunction with `server.close` to reap `keep-alive` connections. Using it > won't cause any harm though, and it can be useful to ensure backwards > compatibility for libraries and applications that need to support versions > older than 19.0.0. Whenever using this in conjunction with `server.close`, > calling this \_after\_ `server.close` is recommended as to avoid race > conditions where new connections are created between a call to this and a > call to `server.close`. ```js const http = require('node:http'); const server = http.createServer({ keepAliveTimeout: 60000 }, (req, res) => { res.writeHead(200, { 'Content-Type': 'application/json' }); res.end(JSON.stringify({ data: 'Hello World!', })); }); server.listen(8000); // Close the server after 10 seconds setTimeout(() => { server.close(() => { console.log('server on port 8000 closed successfully'); }); // Closes idle connections, such as keep-alive connections. Server will close // once remaining active connections are terminated server.closeIdleConnections(); }, 10000); ``` ### `server.headersTimeout` \* Type: {number} \*\*Default:\*\* The minimum between [`server.requestTimeout`][] or `60000`. Limit the amount of time the parser will wait to receive the complete HTTP headers. If the timeout expires, the server responds with status 408 without forwarding the request to the request listener and then closes the connection. It must be set to a non-zero value (e.g. 120 seconds) to protect against potential Denial-of-Service attacks in case the server is deployed without a reverse proxy in front. ### `server.listen()` Starts the HTTP server listening for connections. This method is identical to [`server.listen()`][] from [`net.Server`][]. ### `server.listening` \* Type: {boolean} Indicates whether or not the server is listening for connections. ### `server.maxHeadersCount` \* Type: {number} \*\*Default:\*\* `2000` Limits maximum incoming headers count. If set to 0, no limit will be applied. ### `server.requestTimeout` \* | https://github.com/nodejs/node/blob/main//doc/api/http.md | main | nodejs | [
-0.09950169920921326,
0.03166797012090683,
0.0063164494931697845,
0.034570734947919846,
-0.02599731832742691,
-0.06995286047458649,
-0.03603838011622429,
-0.010637909173965454,
0.0671464130282402,
0.00949303712695837,
-0.06814954429864883,
0.08257094025611877,
-0.06933722645044327,
-0.0332... | 0.078084 |
listening for connections. This method is identical to [`server.listen()`][] from [`net.Server`][]. ### `server.listening` \* Type: {boolean} Indicates whether or not the server is listening for connections. ### `server.maxHeadersCount` \* Type: {number} \*\*Default:\*\* `2000` Limits maximum incoming headers count. If set to 0, no limit will be applied. ### `server.requestTimeout` \* Type: {number} \*\*Default:\*\* `300000` Sets the timeout value in milliseconds for receiving the entire request from the client. If the timeout expires, the server responds with status 408 without forwarding the request to the request listener and then closes the connection. It must be set to a non-zero value (e.g. 120 seconds) to protect against potential Denial-of-Service attacks in case the server is deployed without a reverse proxy in front. ### `server.setTimeout([msecs][, callback])` \* `msecs` {number} \*\*Default:\*\* 0 (no timeout) \* `callback` {Function} \* Returns: {http.Server} Sets the timeout value for sockets, and emits a `'timeout'` event on the Server object, passing the socket as an argument, if a timeout occurs. If there is a `'timeout'` event listener on the Server object, then it will be called with the timed-out socket as an argument. By default, the Server does not timeout sockets. However, if a callback is assigned to the Server's `'timeout'` event, timeouts must be handled explicitly. ### `server.maxRequestsPerSocket` \* Type: {number} Requests per socket. \*\*Default:\*\* 0 (no limit) The maximum number of requests socket can handle before closing keep alive connection. A value of `0` will disable the limit. When the limit is reached it will set the `Connection` header value to `close`, but will not actually close the connection, subsequent requests sent after the limit is reached will get `503 Service Unavailable` as a response. ### `server.timeout` \* Type: {number} Timeout in milliseconds. \*\*Default:\*\* 0 (no timeout) The number of milliseconds of inactivity before a socket is presumed to have timed out. A value of `0` will disable the timeout behavior on incoming connections. The socket timeout logic is set up on connection, so changing this value only affects new connections to the server, not any existing connections. ### `server.keepAliveTimeout` \* Type: {number} Timeout in milliseconds. \*\*Default:\*\* `5000` (5 seconds). The number of milliseconds of inactivity a server needs to wait for additional incoming data, after it has finished writing the last response, before a socket will be destroyed. This timeout value is combined with the [`server.keepAliveTimeoutBuffer`][] option to determine the actual socket timeout, calculated as: socketTimeout = keepAliveTimeout + keepAliveTimeoutBuffer If the server receives new data before the keep-alive timeout has fired, it will reset the regular inactivity timeout, i.e., [`server.timeout`][]. A value of `0` will disable the keep-alive timeout behavior on incoming connections. A value of `0` makes the HTTP server behave similarly to Node.js versions prior to 8.0.0, which did not have a keep-alive timeout. The socket timeout logic is set up on connection, so changing this value only affects new connections to the server, not any existing connections. ### `server.keepAliveTimeoutBuffer` \* Type: {number} Timeout in milliseconds. \*\*Default:\*\* `1000` (1 second). An additional buffer time added to the [`server.keepAliveTimeout`][] to extend the internal socket timeout. This buffer helps reduce connection reset (`ECONNRESET`) errors by increasing the socket timeout slightly beyond the advertised keep-alive timeout. This option applies only to new incoming connections. ### `server[Symbol.asyncDispose]()` Calls [`server.close()`][] and returns a promise that fulfills when the server has closed. ## Class: `http.ServerResponse` \* Extends: {http.OutgoingMessage} This object is created internally by an HTTP server, not by the user. It is passed as the second parameter to the [`'request'`][] event. ### Event: `'close'` Indicates that the response is completed, or its underlying connection was terminated prematurely (before | https://github.com/nodejs/node/blob/main//doc/api/http.md | main | nodejs | [
-0.06164109706878662,
0.03495290130376816,
-0.05172357335686684,
0.016891084611415863,
-0.07449203729629517,
-0.07118003070354462,
-0.0021077257115393877,
0.003661121940240264,
0.031026694923639297,
0.011979431845247746,
-0.06516434252262115,
0.06280403584241867,
0.016706399619579315,
-0.0... | 0.087617 |
server has closed. ## Class: `http.ServerResponse` \* Extends: {http.OutgoingMessage} This object is created internally by an HTTP server, not by the user. It is passed as the second parameter to the [`'request'`][] event. ### Event: `'close'` Indicates that the response is completed, or its underlying connection was terminated prematurely (before the response completion). ### Event: `'finish'` Emitted when the response has been sent. More specifically, this event is emitted when the last segment of the response headers and body have been handed off to the operating system for transmission over the network. It does not imply that the client has received anything yet. ### `response.addTrailers(headers)` \* `headers` {Object} This method adds HTTP trailing headers (a header but at the end of the message) to the response. Trailers will \*\*only\*\* be emitted if chunked encoding is used for the response; if it is not (e.g. if the request was HTTP/1.0), they will be silently discarded. HTTP requires the `Trailer` header to be sent in order to emit trailers, with a list of the header fields in its value. E.g., ```js response.writeHead(200, { 'Content-Type': 'text/plain', 'Trailer': 'Content-MD5' }); response.write(fileData); response.addTrailers({ 'Content-MD5': '7895bf4b8828b55ceaf47747b4bca667' }); response.end(); ``` Attempting to set a header field name or value that contains invalid characters will result in a [`TypeError`][] being thrown. ### `response.connection` > Stability: 0 - Deprecated. Use [`response.socket`][]. \* Type: {stream.Duplex} See [`response.socket`][]. ### `response.cork()` See [`writable.cork()`][]. ### `response.end([data[, encoding]][, callback])` \* `data` {string|Buffer|Uint8Array} \* `encoding` {string} \* `callback` {Function} \* Returns: {this} This method signals to the server that all of the response headers and body have been sent; that server should consider this message complete. The method, `response.end()`, MUST be called on each response. If `data` is specified, it is similar in effect to calling [`response.write(data, encoding)`][] followed by `response.end(callback)`. If `callback` is specified, it will be called when the response stream is finished. ### `response.finished` > Stability: 0 - Deprecated. Use [`response.writableEnded`][]. \* Type: {boolean} The `response.finished` property will be `true` if [`response.end()`][] has been called. ### `response.flushHeaders()` Flushes the response headers. See also: [`request.flushHeaders()`][]. ### `response.getHeader(name)` \* `name` {string} \* Returns: {number | string | string\[] | undefined} Reads out a header that's already been queued but not sent to the client. The name is case-insensitive. The type of the return value depends on the arguments provided to [`response.setHeader()`][]. ```js response.setHeader('Content-Type', 'text/html'); response.setHeader('Content-Length', Buffer.byteLength(body)); response.setHeader('Set-Cookie', ['type=ninja', 'language=javascript']); const contentType = response.getHeader('content-type'); // contentType is 'text/html' const contentLength = response.getHeader('Content-Length'); // contentLength is of type number const setCookie = response.getHeader('set-cookie'); // setCookie is of type string[] ``` ### `response.getHeaderNames()` \* Returns: {string\[]} Returns an array containing the unique names of the current outgoing headers. All header names are lowercase. ```js response.setHeader('Foo', 'bar'); response.setHeader('Set-Cookie', ['foo=bar', 'bar=baz']); const headerNames = response.getHeaderNames(); // headerNames === ['foo', 'set-cookie'] ``` ### `response.getHeaders()` \* Returns: {Object} Returns a shallow copy of the current outgoing headers. Since a shallow copy is used, array values may be mutated without additional calls to various header-related http module methods. The keys of the returned object are the header names and the values are the respective header values. All header names are lowercase. The object returned by the `response.getHeaders()` method \_does not\_ prototypically inherit from the JavaScript `Object`. This means that typical `Object` methods such as `obj.toString()`, `obj.hasOwnProperty()`, and others are not defined and \_will not work\_. ```js response.setHeader('Foo', 'bar'); response.setHeader('Set-Cookie', ['foo=bar', 'bar=baz']); const headers = response.getHeaders(); // headers === { foo: 'bar', 'set-cookie': ['foo=bar', 'bar=baz'] } ``` ### `response.hasHeader(name)` \* `name` {string} \* Returns: {boolean} Returns `true` if the header identified by `name` is currently set in the outgoing headers. The header name | https://github.com/nodejs/node/blob/main//doc/api/http.md | main | nodejs | [
-0.07819896191358566,
0.026306696236133575,
0.05793606489896774,
0.02372489497065544,
0.06813618540763855,
-0.0839061588048935,
0.0290977880358696,
-0.02348453924059868,
0.10607592761516571,
0.03575529903173447,
-0.02851182594895363,
0.04050597548484802,
-0.057807475328445435,
-0.026204755... | 0.117772 |
\_will not work\_. ```js response.setHeader('Foo', 'bar'); response.setHeader('Set-Cookie', ['foo=bar', 'bar=baz']); const headers = response.getHeaders(); // headers === { foo: 'bar', 'set-cookie': ['foo=bar', 'bar=baz'] } ``` ### `response.hasHeader(name)` \* `name` {string} \* Returns: {boolean} Returns `true` if the header identified by `name` is currently set in the outgoing headers. The header name matching is case-insensitive. ```js const hasContentType = response.hasHeader('content-type'); ``` ### `response.headersSent` \* Type: {boolean} Boolean (read-only). True if headers were sent, false otherwise. ### `response.removeHeader(name)` \* `name` {string} Removes a header that's queued for implicit sending. ```js response.removeHeader('Content-Encoding'); ``` ### `response.req` \* Type: {http.IncomingMessage} A reference to the original HTTP `request` object. ### `response.sendDate` \* Type: {boolean} When true, the Date header will be automatically generated and sent in the response if it is not already present in the headers. Defaults to true. This should only be disabled for testing; HTTP requires the Date header in responses. ### `response.setHeader(name, value)` \* `name` {string} \* `value` {number | string | string\[]} \* Returns: {http.ServerResponse} Returns the response object. Sets a single header value for implicit headers. If this header already exists in the to-be-sent headers, its value will be replaced. Use an array of strings here to send multiple headers with the same name. Non-string values will be stored without modification. Therefore, [`response.getHeader()`][] may return non-string values. However, the non-string values will be converted to strings for network transmission. The same response object is returned to the caller, to enable call chaining. ```js response.setHeader('Content-Type', 'text/html'); ``` or ```js response.setHeader('Set-Cookie', ['type=ninja', 'language=javascript']); ``` Attempting to set a header field name or value that contains invalid characters will result in a [`TypeError`][] being thrown. When headers have been set with [`response.setHeader()`][], they will be merged with any headers passed to [`response.writeHead()`][], with the headers passed to [`response.writeHead()`][] given precedence. ```js // Returns content-type = text/plain const server = http.createServer((req, res) => { res.setHeader('Content-Type', 'text/html'); res.setHeader('X-Foo', 'bar'); res.writeHead(200, { 'Content-Type': 'text/plain' }); res.end('ok'); }); ``` If [`response.writeHead()`][] method is called and this method has not been called, it will directly write the supplied header values onto the network channel without caching internally, and the [`response.getHeader()`][] on the header will not yield the expected result. If progressive population of headers is desired with potential future retrieval and modification, use [`response.setHeader()`][] instead of [`response.writeHead()`][]. ### `response.setTimeout(msecs[, callback])` \* `msecs` {number} \* `callback` {Function} \* Returns: {http.ServerResponse} Sets the Socket's timeout value to `msecs`. If a callback is provided, then it is added as a listener on the `'timeout'` event on the response object. If no `'timeout'` listener is added to the request, the response, or the server, then sockets are destroyed when they time out. If a handler is assigned to the request, the response, or the server's `'timeout'` events, timed out sockets must be handled explicitly. ### `response.socket` \* Type: {stream.Duplex} Reference to the underlying socket. Usually users will not want to access this property. In particular, the socket will not emit `'readable'` events because of how the protocol parser attaches to the socket. After `response.end()`, the property is nulled. ```mjs import http from 'node:http'; const server = http.createServer((req, res) => { const ip = res.socket.remoteAddress; const port = res.socket.remotePort; res.end(`Your IP address is ${ip} and your source port is ${port}.`); }).listen(3000); ``` ```cjs const http = require('node:http'); const server = http.createServer((req, res) => { const ip = res.socket.remoteAddress; const port = res.socket.remotePort; res.end(`Your IP address is ${ip} and your source port is ${port}.`); }).listen(3000); ``` This property is guaranteed to be an instance of the {net.Socket} class, a subclass of {stream.Duplex}, unless the user specified a socket type other than {net.Socket}. ### `response.statusCode` \* | https://github.com/nodejs/node/blob/main//doc/api/http.md | main | nodejs | [
-0.10841227322816849,
0.09595014899969101,
0.032061267644166946,
0.0037553906440734863,
0.0018337987130507827,
-0.04332446679472923,
0.07628507912158966,
0.036843255162239075,
0.01133811566978693,
-0.02777807042002678,
-0.05404653400182724,
-0.046904925256967545,
-0.0000342610219377093,
0.... | -0.003533 |
const ip = res.socket.remoteAddress; const port = res.socket.remotePort; res.end(`Your IP address is ${ip} and your source port is ${port}.`); }).listen(3000); ``` This property is guaranteed to be an instance of the {net.Socket} class, a subclass of {stream.Duplex}, unless the user specified a socket type other than {net.Socket}. ### `response.statusCode` \* Type: {number} \*\*Default:\*\* `200` When using implicit headers (not calling [`response.writeHead()`][] explicitly), this property controls the status code that will be sent to the client when the headers get flushed. ```js response.statusCode = 404; ``` After response header was sent to the client, this property indicates the status code which was sent out. ### `response.statusMessage` \* Type: {string} When using implicit headers (not calling [`response.writeHead()`][] explicitly), this property controls the status message that will be sent to the client when the headers get flushed. If this is left as `undefined` then the standard message for the status code will be used. ```js response.statusMessage = 'Not found'; ``` After response header was sent to the client, this property indicates the status message which was sent out. ### `response.strictContentLength` \* Type: {boolean} \*\*Default:\*\* `false` If set to `true`, Node.js will check whether the `Content-Length` header value and the size of the body, in bytes, are equal. Mismatching the `Content-Length` header value will result in an `Error` being thrown, identified by `code:` [`'ERR\_HTTP\_CONTENT\_LENGTH\_MISMATCH'`][]. ### `response.uncork()` See [`writable.uncork()`][]. ### `response.writableEnded` \* Type: {boolean} Is `true` after [`response.end()`][] has been called. This property does not indicate whether the data has been flushed, for this use [`response.writableFinished`][] instead. ### `response.writableFinished` \* Type: {boolean} Is `true` if all data has been flushed to the underlying system, immediately before the [`'finish'`][] event is emitted. ### `response.write(chunk[, encoding][, callback])` \* `chunk` {string|Buffer|Uint8Array} \* `encoding` {string} \*\*Default:\*\* `'utf8'` \* `callback` {Function} \* Returns: {boolean} If this method is called and [`response.writeHead()`][] has not been called, it will switch to implicit header mode and flush the implicit headers. This sends a chunk of the response body. This method may be called multiple times to provide successive parts of the body. If `rejectNonStandardBodyWrites` is set to true in `createServer` then writing to the body is not allowed when the request method or response status do not support content. If an attempt is made to write to the body for a HEAD request or as part of a `204` or `304`response, a synchronous `Error` with the code `ERR\_HTTP\_BODY\_NOT\_ALLOWED` is thrown. `chunk` can be a string or a buffer. If `chunk` is a string, the second parameter specifies how to encode it into a byte stream. `callback` will be called when this chunk of data is flushed. This is the raw HTTP body and has nothing to do with higher-level multi-part body encodings that may be used. The first time [`response.write()`][] is called, it will send the buffered header information and the first chunk of the body to the client. The second time [`response.write()`][] is called, Node.js assumes data will be streamed, and sends the new data separately. That is, the response is buffered up to the first chunk of the body. Returns `true` if the entire data was flushed successfully to the kernel buffer. Returns `false` if all or part of the data was queued in user memory. `'drain'` will be emitted when the buffer is free again. ### `response.writeContinue()` Sends an HTTP/1.1 100 Continue message to the client, indicating that the request body should be sent. See the [`'checkContinue'`][] event on `Server`. ### `response.writeEarlyHints(hints[, callback])` \* `hints` {Object} \* `callback` {Function} Sends an HTTP/1.1 103 Early Hints message to the client with a Link header, indicating that the user agent can preload/preconnect | https://github.com/nodejs/node/blob/main//doc/api/http.md | main | nodejs | [
-0.0895513966679573,
0.07353836297988892,
0.010532708838582039,
0.018555888906121254,
-0.011344240047037601,
-0.02010672353208065,
-0.0030754483304917812,
0.007017000112682581,
0.0605645477771759,
0.019493218511343002,
-0.04907814785838127,
0.0652339830994606,
-0.03669726476073265,
0.02462... | 0.097919 |
100 Continue message to the client, indicating that the request body should be sent. See the [`'checkContinue'`][] event on `Server`. ### `response.writeEarlyHints(hints[, callback])` \* `hints` {Object} \* `callback` {Function} Sends an HTTP/1.1 103 Early Hints message to the client with a Link header, indicating that the user agent can preload/preconnect the linked resources. The `hints` is an object containing the values of headers to be sent with early hints message. The optional `callback` argument will be called when the response message has been written. \*\*Example\*\* ```js const earlyHintsLink = '; rel=preload; as=style'; response.writeEarlyHints({ 'link': earlyHintsLink, }); const earlyHintsLinks = [ '; rel=preload; as=style', '; rel=preload; as=script', ]; response.writeEarlyHints({ 'link': earlyHintsLinks, 'x-trace-id': 'id for diagnostics', }); const earlyHintsCallback = () => console.log('early hints message sent'); response.writeEarlyHints({ 'link': earlyHintsLinks, }, earlyHintsCallback); ``` ### `response.writeHead(statusCode[, statusMessage][, headers])` \* `statusCode` {number} \* `statusMessage` {string} \* `headers` {Object|Array} \* Returns: {http.ServerResponse} Sends a response header to the request. The status code is a 3-digit HTTP status code, like `404`. The last argument, `headers`, are the response headers. Optionally one can give a human-readable `statusMessage` as the second argument. `headers` may be an `Array` where the keys and values are in the same list. It is \_not\_ a list of tuples. So, the even-numbered offsets are key values, and the odd-numbered offsets are the associated values. The array is in the same format as `request.rawHeaders`. Returns a reference to the `ServerResponse`, so that calls can be chained. ```js const body = 'hello world'; response .writeHead(200, { 'Content-Length': Buffer.byteLength(body), 'Content-Type': 'text/plain', }) .end(body); ``` This method must only be called once on a message and it must be called before [`response.end()`][] is called. If [`response.write()`][] or [`response.end()`][] are called before calling this, the implicit/mutable headers will be calculated and call this function. When headers have been set with [`response.setHeader()`][], they will be merged with any headers passed to [`response.writeHead()`][], with the headers passed to [`response.writeHead()`][] given precedence. If this method is called and [`response.setHeader()`][] has not been called, it will directly write the supplied header values onto the network channel without caching internally, and the [`response.getHeader()`][] on the header will not yield the expected result. If progressive population of headers is desired with potential future retrieval and modification, use [`response.setHeader()`][] instead. ```js // Returns content-type = text/plain const server = http.createServer((req, res) => { res.setHeader('Content-Type', 'text/html'); res.setHeader('X-Foo', 'bar'); res.writeHead(200, { 'Content-Type': 'text/plain' }); res.end('ok'); }); ``` `Content-Length` is read in bytes, not characters. Use [`Buffer.byteLength()`][] to determine the length of the body in bytes. Node.js will check whether `Content-Length` and the length of the body which has been transmitted are equal or not. Attempting to set a header field name or value that contains invalid characters will result in a [`TypeError`][] being thrown. ### `response.writeProcessing()` Sends a HTTP/1.1 102 Processing message to the client, indicating that the request body should be sent. ## Class: `http.IncomingMessage` \* Extends: {stream.Readable} An `IncomingMessage` object is created by [`http.Server`][] or [`http.ClientRequest`][] and passed as the first argument to the [`'request'`][] and [`'response'`][] event respectively. It may be used to access response status, headers, and data. Different from its `socket` value which is a subclass of {stream.Duplex}, the `IncomingMessage` itself extends {stream.Readable} and is created separately to parse and emit the incoming HTTP headers and payload, as the underlying socket may be reused multiple times in case of keep-alive. ### Event: `'aborted'` > Stability: 0 - Deprecated. Listen for `'close'` event instead. Emitted when the request has been aborted. ### Event: `'close'` Emitted when the request has been completed. ### `message.aborted` > Stability: 0 - Deprecated. Check `message.destroyed` from {stream.Readable}. \* Type: | https://github.com/nodejs/node/blob/main//doc/api/http.md | main | nodejs | [
-0.08002807945013046,
0.05844775214791298,
0.060069113969802856,
0.08617547899484634,
-0.0029469269793480635,
-0.03612576052546501,
0.03868984803557396,
0.029566969722509384,
0.07137428969144821,
-0.04770779237151146,
-0.034179266542196274,
0.06469467282295227,
-0.03248743712902069,
-0.031... | 0.062596 |
reused multiple times in case of keep-alive. ### Event: `'aborted'` > Stability: 0 - Deprecated. Listen for `'close'` event instead. Emitted when the request has been aborted. ### Event: `'close'` Emitted when the request has been completed. ### `message.aborted` > Stability: 0 - Deprecated. Check `message.destroyed` from {stream.Readable}. \* Type: {boolean} The `message.aborted` property will be `true` if the request has been aborted. ### `message.complete` \* Type: {boolean} The `message.complete` property will be `true` if a complete HTTP message has been received and successfully parsed. This property is particularly useful as a means of determining if a client or server fully transmitted a message before a connection was terminated: ```js const req = http.request({ host: '127.0.0.1', port: 8080, method: 'POST', }, (res) => { res.resume(); res.on('end', () => { if (!res.complete) console.error( 'The connection was terminated while the message was still being sent'); }); }); ``` ### `message.connection` > Stability: 0 - Deprecated. Use [`message.socket`][]. Alias for [`message.socket`][]. ### `message.destroy([error])` \* `error` {Error} \* Returns: {this} Calls `destroy()` on the socket that received the `IncomingMessage`. If `error` is provided, an `'error'` event is emitted on the socket and `error` is passed as an argument to any listeners on the event. ### `message.headers` \* Type: {Object} The request/response headers object. Key-value pairs of header names and values. Header names are lower-cased. ```js // Prints something like: // // { 'user-agent': 'curl/7.22.0', // host: '127.0.0.1:8000', // accept: '\*/\*' } console.log(request.headers); ``` Duplicates in raw headers are handled in the following ways, depending on the header name: \* Duplicates of `age`, `authorization`, `content-length`, `content-type`, `etag`, `expires`, `from`, `host`, `if-modified-since`, `if-unmodified-since`, `last-modified`, `location`, `max-forwards`, `proxy-authorization`, `referer`, `retry-after`, `server`, or `user-agent` are discarded. To allow duplicate values of the headers listed above to be joined, use the option `joinDuplicateHeaders` in [`http.request()`][] and [`http.createServer()`][]. See RFC 9110 Section 5.3 for more information. \* `set-cookie` is always an array. Duplicates are added to the array. \* For duplicate `cookie` headers, the values are joined together with `; `. \* For all other headers, the values are joined together with `, `. ### `message.headersDistinct` \* Type: {Object} Similar to [`message.headers`][], but there is no join logic and the values are always arrays of strings, even for headers received just once. ```js // Prints something like: // // { 'user-agent': ['curl/7.22.0'], // host: ['127.0.0.1:8000'], // accept: ['\*/\*'] } console.log(request.headersDistinct); ``` ### `message.httpVersion` \* Type: {string} In case of server request, the HTTP version sent by the client. In the case of client response, the HTTP version of the connected-to server. Probably either `'1.1'` or `'1.0'`. Also `message.httpVersionMajor` is the first integer and `message.httpVersionMinor` is the second. ### `message.method` \* Type: {string} \*\*Only valid for request obtained from [`http.Server`][].\*\* The request method as a string. Read only. Examples: `'GET'`, `'DELETE'`. ### `message.rawHeaders` \* Type: {string\[]} The raw request/response headers list exactly as they were received. The keys and values are in the same list. It is \_not\_ a list of tuples. So, the even-numbered offsets are key values, and the odd-numbered offsets are the associated values. Header names are not lowercased, and duplicates are not merged. ```js // Prints something like: // // [ 'user-agent', // 'this is invalid because there can be only one', // 'User-Agent', // 'curl/7.22.0', // 'Host', // '127.0.0.1:8000', // 'ACCEPT', // '\*/\*' ] console.log(request.rawHeaders); ``` ### `message.rawTrailers` \* Type: {string\[]} The raw request/response trailer keys and values exactly as they were received. Only populated at the `'end'` event. ### `message.setTimeout(msecs[, callback])` \* `msecs` {number} \* `callback` {Function} \* Returns: {http.IncomingMessage} Calls `message.socket.setTimeout(msecs, callback)`. ### `message.socket` \* Type: {stream.Duplex} The [`net.Socket`][] object associated with the connection. | https://github.com/nodejs/node/blob/main//doc/api/http.md | main | nodejs | [
-0.06272564083337784,
0.06722141802310944,
0.029778558760881424,
0.05490460246801376,
0.07109693437814713,
-0.06903401017189026,
0.0013578914804384112,
-0.058491334319114685,
0.10803249478340149,
0.006761112716048956,
-0.013378134928643703,
0.07975183427333832,
-0.03972216695547104,
0.0307... | 0.083741 |
### `message.rawTrailers` \* Type: {string\[]} The raw request/response trailer keys and values exactly as they were received. Only populated at the `'end'` event. ### `message.setTimeout(msecs[, callback])` \* `msecs` {number} \* `callback` {Function} \* Returns: {http.IncomingMessage} Calls `message.socket.setTimeout(msecs, callback)`. ### `message.socket` \* Type: {stream.Duplex} The [`net.Socket`][] object associated with the connection. With HTTPS support, use [`request.socket.getPeerCertificate()`][] to obtain the client's authentication details. This property is guaranteed to be an instance of the {net.Socket} class, a subclass of {stream.Duplex}, unless the user specified a socket type other than {net.Socket} or internally nulled. ### `message.statusCode` \* Type: {number} \*\*Only valid for response obtained from [`http.ClientRequest`][].\*\* The 3-digit HTTP response status code. E.G. `404`. ### `message.statusMessage` \* Type: {string} \*\*Only valid for response obtained from [`http.ClientRequest`][].\*\* The HTTP response status message (reason phrase). E.G. `OK` or `Internal Server Error`. ### `message.trailers` \* Type: {Object} The request/response trailers object. Only populated at the `'end'` event. ### `message.trailersDistinct` \* Type: {Object} Similar to [`message.trailers`][], but there is no join logic and the values are always arrays of strings, even for headers received just once. Only populated at the `'end'` event. ### `message.url` \* Type: {string} \*\*Only valid for request obtained from [`http.Server`][].\*\* Request URL string. This contains only the URL that is present in the actual HTTP request. Take the following request: ```http GET /status?name=ryan HTTP/1.1 Accept: text/plain ``` To parse the URL into its parts: ```js new URL(`http://${process.env.HOST ?? 'localhost'}${request.url}`); ``` When `request.url` is `'/status?name=ryan'` and `process.env.HOST` is undefined: ```console $ node > new URL(`http://${process.env.HOST ?? 'localhost'}${request.url}`); URL { href: 'http://localhost/status?name=ryan', origin: 'http://localhost', protocol: 'http:', username: '', password: '', host: 'localhost', hostname: 'localhost', port: '', pathname: '/status', search: '?name=ryan', searchParams: URLSearchParams { 'name' => 'ryan' }, hash: '' } ``` Ensure that you set `process.env.HOST` to the server's host name, or consider replacing this part entirely. If using `req.headers.host`, ensure proper validation is used, as clients may specify a custom `Host` header. ## Class: `http.OutgoingMessage` \* Extends: {Stream} This class serves as the parent class of [`http.ClientRequest`][] and [`http.ServerResponse`][]. It is an abstract outgoing message from the perspective of the participants of an HTTP transaction. ### Event: `'drain'` Emitted when the buffer of the message is free again. ### Event: `'finish'` Emitted when the transmission is finished successfully. ### Event: `'prefinish'` Emitted after `outgoingMessage.end()` is called. When the event is emitted, all data has been processed but not necessarily completely flushed. ### `outgoingMessage.addTrailers(headers)` \* `headers` {Object} Adds HTTP trailers (headers but at the end of the message) to the message. Trailers will \*\*only\*\* be emitted if the message is chunked encoded. If not, the trailers will be silently discarded. HTTP requires the `Trailer` header to be sent to emit trailers, with a list of header field names in its value, e.g. ```js message.writeHead(200, { 'Content-Type': 'text/plain', 'Trailer': 'Content-MD5' }); message.write(fileData); message.addTrailers({ 'Content-MD5': '7895bf4b8828b55ceaf47747b4bca667' }); message.end(); ``` Attempting to set a header field name or value that contains invalid characters will result in a `TypeError` being thrown. ### `outgoingMessage.appendHeader(name, value)` \* `name` {string} Header name \* `value` {string|string\[]} Header value \* Returns: {this} Append a single header value to the header object. If the value is an array, this is equivalent to calling this method multiple times. If there were no previous values for the header, this is equivalent to calling [`outgoingMessage.setHeader(name, value)`][]. Depending of the value of `options.uniqueHeaders` when the client request or the server were created, this will end up in the header being sent multiple times or a single time with values joined using `; `. ### `outgoingMessage.connection` > Stability: 0 - Deprecated: Use [`outgoingMessage.socket`][] instead. Alias of [`outgoingMessage.socket`][]. ### `outgoingMessage.cork()` See [`writable.cork()`][]. | https://github.com/nodejs/node/blob/main//doc/api/http.md | main | nodejs | [
-0.08952448517084122,
0.039483580738306046,
-0.024522805586457253,
0.05582057684659958,
-0.02143007144331932,
-0.08731497079133987,
0.011487885378301144,
0.02765471301972866,
0.10853616893291473,
-0.022745918482542038,
-0.018467310816049576,
0.022056782618165016,
-0.015239975415170193,
0.0... | 0.02476 |
value of `options.uniqueHeaders` when the client request or the server were created, this will end up in the header being sent multiple times or a single time with values joined using `; `. ### `outgoingMessage.connection` > Stability: 0 - Deprecated: Use [`outgoingMessage.socket`][] instead. Alias of [`outgoingMessage.socket`][]. ### `outgoingMessage.cork()` See [`writable.cork()`][]. ### `outgoingMessage.destroy([error])` \* `error` {Error} Optional, an error to emit with `error` event \* Returns: {this} Destroys the message. Once a socket is associated with the message and is connected, that socket will be destroyed as well. ### `outgoingMessage.end(chunk[, encoding][, callback])` \* `chunk` {string|Buffer|Uint8Array} \* `encoding` {string} Optional, \*\*Default\*\*: `utf8` \* `callback` {Function} Optional \* Returns: {this} Finishes the outgoing message. If any parts of the body are unsent, it will flush them to the underlying system. If the message is chunked, it will send the terminating chunk `0\r\n\r\n`, and send the trailers (if any). If `chunk` is specified, it is equivalent to calling `outgoingMessage.write(chunk, encoding)`, followed by `outgoingMessage.end(callback)`. If `callback` is provided, it will be called when the message is finished (equivalent to a listener of the `'finish'` event). ### `outgoingMessage.flushHeaders()` Flushes the message headers. For efficiency reason, Node.js normally buffers the message headers until `outgoingMessage.end()` is called or the first chunk of message data is written. It then tries to pack the headers and data into a single TCP packet. It is usually desired (it saves a TCP round-trip), but not when the first data is not sent until possibly much later. `outgoingMessage.flushHeaders()` bypasses the optimization and kickstarts the message. ### `outgoingMessage.getHeader(name)` \* `name` {string} Name of header \* Returns: {number | string | string\[] | undefined} Gets the value of the HTTP header with the given name. If that header is not set, the returned value will be `undefined`. ### `outgoingMessage.getHeaderNames()` \* Returns: {string\[]} Returns an array containing the unique names of the current outgoing headers. All names are lowercase. ### `outgoingMessage.getHeaders()` \* Returns: {Object} Returns a shallow copy of the current outgoing headers. Since a shallow copy is used, array values may be mutated without additional calls to various header-related HTTP module methods. The keys of the returned object are the header names and the values are the respective header values. All header names are lowercase. The object returned by the `outgoingMessage.getHeaders()` method does not prototypically inherit from the JavaScript `Object`. This means that typical `Object` methods such as `obj.toString()`, `obj.hasOwnProperty()`, and others are not defined and will not work. ```js outgoingMessage.setHeader('Foo', 'bar'); outgoingMessage.setHeader('Set-Cookie', ['foo=bar', 'bar=baz']); const headers = outgoingMessage.getHeaders(); // headers === { foo: 'bar', 'set-cookie': ['foo=bar', 'bar=baz'] } ``` ### `outgoingMessage.hasHeader(name)` \* `name` {string} \* Returns: {boolean} Returns `true` if the header identified by `name` is currently set in the outgoing headers. The header name is case-insensitive. ```js const hasContentType = outgoingMessage.hasHeader('content-type'); ``` ### `outgoingMessage.headersSent` \* Type: {boolean} Read-only. `true` if the headers were sent, otherwise `false`. ### `outgoingMessage.pipe()` Overrides the `stream.pipe()` method inherited from the legacy `Stream` class which is the parent class of `http.OutgoingMessage`. Calling this method will throw an `Error` because `outgoingMessage` is a write-only stream. ### `outgoingMessage.removeHeader(name)` \* `name` {string} Header name Removes a header that is queued for implicit sending. ```js outgoingMessage.removeHeader('Content-Encoding'); ``` ### `outgoingMessage.setHeader(name, value)` \* `name` {string} Header name \* `value` {number | string | string\[]} Header value \* Returns: {this} Sets a single header value. If the header already exists in the to-be-sent headers, its value will be replaced. Use an array of strings to send multiple headers with the same name. ### `outgoingMessage.setHeaders(headers)` \* `headers` {Headers|Map} \* Returns: {this} Sets multiple header values for implicit headers. `headers` must be an instance of [`Headers`][] or `Map`, | https://github.com/nodejs/node/blob/main//doc/api/http.md | main | nodejs | [
-0.07901723682880402,
0.01786295510828495,
0.003367044497281313,
0.03251553326845169,
-0.03140406683087349,
-0.0960800051689148,
0.08795768022537231,
0.023458430543541908,
0.034415509551763535,
-0.04077078402042389,
0.0018593281274661422,
-0.00449779536575079,
-0.0037181228399276733,
0.047... | 0.04116 |
the header already exists in the to-be-sent headers, its value will be replaced. Use an array of strings to send multiple headers with the same name. ### `outgoingMessage.setHeaders(headers)` \* `headers` {Headers|Map} \* Returns: {this} Sets multiple header values for implicit headers. `headers` must be an instance of [`Headers`][] or `Map`, if a header already exists in the to-be-sent headers, its value will be replaced. ```js const headers = new Headers({ foo: 'bar' }); outgoingMessage.setHeaders(headers); ``` or ```js const headers = new Map([['foo', 'bar']]); outgoingMessage.setHeaders(headers); ``` When headers have been set with [`outgoingMessage.setHeaders()`][], they will be merged with any headers passed to [`response.writeHead()`][], with the headers passed to [`response.writeHead()`][] given precedence. ```js // Returns content-type = text/plain const server = http.createServer((req, res) => { const headers = new Headers({ 'Content-Type': 'text/html' }); res.setHeaders(headers); res.writeHead(200, { 'Content-Type': 'text/plain' }); res.end('ok'); }); ``` ### `outgoingMessage.setTimeout(msecs[, callback])` \* `msecs` {number} \* `callback` {Function} Optional function to be called when a timeout occurs. Same as binding to the `timeout` event. \* Returns: {this} Once a socket is associated with the message and is connected, [`socket.setTimeout()`][] will be called with `msecs` as the first parameter. ### `outgoingMessage.socket` \* Type: {stream.Duplex} Reference to the underlying socket. Usually, users will not want to access this property. After calling `outgoingMessage.end()`, this property will be nulled. ### `outgoingMessage.uncork()` See [`writable.uncork()`][] ### `outgoingMessage.writableCorked` \* Type: {number} The number of times `outgoingMessage.cork()` has been called. ### `outgoingMessage.writableEnded` \* Type: {boolean} Is `true` if `outgoingMessage.end()` has been called. This property does not indicate whether the data has been flushed. For that purpose, use `message.writableFinished` instead. ### `outgoingMessage.writableFinished` \* Type: {boolean} Is `true` if all data has been flushed to the underlying system. ### `outgoingMessage.writableHighWaterMark` \* Type: {number} The `highWaterMark` of the underlying socket if assigned. Otherwise, the default buffer level when [`writable.write()`][] starts returning false (`16384`). ### `outgoingMessage.writableLength` \* Type: {number} The number of buffered bytes. ### `outgoingMessage.writableObjectMode` \* Type: {boolean} Always `false`. ### `outgoingMessage.write(chunk[, encoding][, callback])` \* `chunk` {string|Buffer|Uint8Array} \* `encoding` {string} \*\*Default\*\*: `utf8` \* `callback` {Function} \* Returns: {boolean} Sends a chunk of the body. This method can be called multiple times. The `encoding` argument is only relevant when `chunk` is a string. Defaults to `'utf8'`. The `callback` argument is optional and will be called when this chunk of data is flushed. Returns `true` if the entire data was flushed successfully to the kernel buffer. Returns `false` if all or part of the data was queued in the user memory. The `'drain'` event will be emitted when the buffer is free again. ## `http.METHODS` \* Type: {string\[]} A list of the HTTP methods that are supported by the parser. ## `http.STATUS\_CODES` \* Type: {Object} A collection of all the standard HTTP response status codes, and the short description of each. For example, `http.STATUS\_CODES[404] === 'Not Found'`. ## `http.createServer([options][, requestListener])` \* `options` {Object} \* `connectionsCheckingInterval`: Sets the interval value in milliseconds to check for request and headers timeout in incomplete requests. \*\*Default:\*\* `30000`. \* `headersTimeout`: Sets the timeout value in milliseconds for receiving the complete HTTP headers from the client. See [`server.headersTimeout`][] for more information. \*\*Default:\*\* `60000`. \* `highWaterMark` {number} Optionally overrides all `socket`s' `readableHighWaterMark` and `writableHighWaterMark`. This affects `highWaterMark` property of both `IncomingMessage` and `ServerResponse`. \*\*Default:\*\* See [`stream.getDefaultHighWaterMark()`][]. \* `insecureHTTPParser` {boolean} If set to `true`, it will use a HTTP parser with leniency flags enabled. Using the insecure parser should be avoided. See [`--insecure-http-parser`][] for more information. \*\*Default:\*\* `false`. \* `IncomingMessage` {http.IncomingMessage} Specifies the `IncomingMessage` class to be used. Useful for extending the original `IncomingMessage`. \*\*Default:\*\* `IncomingMessage`. \* `joinDuplicateHeaders` {boolean} If set to `true`, this option allows joining the field line | https://github.com/nodejs/node/blob/main//doc/api/http.md | main | nodejs | [
-0.037573594599962234,
0.07197439670562744,
0.08738599717617035,
0.02455773763358593,
0.007710481993854046,
-0.03058500774204731,
0.07672344893217087,
0.03206142038106918,
-0.011200976558029652,
-0.01282249204814434,
-0.06628872454166412,
-0.06896265596151352,
0.032067298889160156,
0.01572... | 0.061894 |
with leniency flags enabled. Using the insecure parser should be avoided. See [`--insecure-http-parser`][] for more information. \*\*Default:\*\* `false`. \* `IncomingMessage` {http.IncomingMessage} Specifies the `IncomingMessage` class to be used. Useful for extending the original `IncomingMessage`. \*\*Default:\*\* `IncomingMessage`. \* `joinDuplicateHeaders` {boolean} If set to `true`, this option allows joining the field line values of multiple headers in a request with a comma (`, `) instead of discarding the duplicates. For more information, refer to [`message.headers`][]. \*\*Default:\*\* `false`. \* `keepAlive` {boolean} If set to `true`, it enables keep-alive functionality on the socket immediately after a new incoming connection is received, similarly on what is done in \[`socket.setKeepAlive([enable][, initialDelay])`]\[`socket.setKeepAlive(enable, initialDelay)`]. \*\*Default:\*\* `false`. \* `keepAliveInitialDelay` {number} If set to a positive number, it sets the initial delay before the first keepalive probe is sent on an idle socket. \*\*Default:\*\* `0`. \* `keepAliveTimeout`: The number of milliseconds of inactivity a server needs to wait for additional incoming data, after it has finished writing the last response, before a socket will be destroyed. See [`server.keepAliveTimeout`][] for more information. \*\*Default:\*\* `5000`. \* `maxHeaderSize` {number} Optionally overrides the value of [`--max-http-header-size`][] for requests received by this server, i.e. the maximum length of request headers in bytes. \*\*Default:\*\* 16384 (16 KiB). \* `noDelay` {boolean} If set to `true`, it disables the use of Nagle's algorithm immediately after a new incoming connection is received. \*\*Default:\*\* `true`. \* `requestTimeout`: Sets the timeout value in milliseconds for receiving the entire request from the client. See [`server.requestTimeout`][] for more information. \*\*Default:\*\* `300000`. \* `requireHostHeader` {boolean} If set to `true`, it forces the server to respond with a 400 (Bad Request) status code to any HTTP/1.1 request message that lacks a Host header (as mandated by the specification). \*\*Default:\*\* `true`. \* `ServerResponse` {http.ServerResponse} Specifies the `ServerResponse` class to be used. Useful for extending the original `ServerResponse`. \*\*Default:\*\* `ServerResponse`. \* `shouldUpgradeCallback(request)` {Function} A callback which receives an incoming request and returns a boolean, to control which upgrade attempts should be accepted. Accepted upgrades will fire an `'upgrade'` event (or their sockets will be destroyed, if no listener is registered) while rejected upgrades will fire a `'request'` event like any non-upgrade request. This options defaults to `() => server.listenerCount('upgrade') > 0`. \* `uniqueHeaders` {Array} A list of response headers that should be sent only once. If the header's value is an array, the items will be joined using `; `. \* `rejectNonStandardBodyWrites` {boolean} If set to `true`, an error is thrown when writing to an HTTP response which does not have a body. \*\*Default:\*\* `false`. \* `optimizeEmptyRequests` {boolean} If set to `true`, requests without `Content-Length` or `Transfer-Encoding` headers (indicating no body) will be initialized with an already-ended body stream, so they will never emit any stream events (like `'data'` or `'end'`). You can use `req.readableEnded` to detect this case. \*\*Default:\*\* `false`. \* `requestListener` {Function} \* Returns: {http.Server} Returns a new instance of [`http.Server`][]. The `requestListener` is a function which is automatically added to the [`'request'`][] event. ```mjs import http from 'node:http'; // Create a local server to receive data from const server = http.createServer((req, res) => { res.writeHead(200, { 'Content-Type': 'application/json' }); res.end(JSON.stringify({ data: 'Hello World!', })); }); server.listen(8000); ``` ```cjs const http = require('node:http'); // Create a local server to receive data from const server = http.createServer((req, res) => { res.writeHead(200, { 'Content-Type': 'application/json' }); res.end(JSON.stringify({ data: 'Hello World!', })); }); server.listen(8000); ``` ```mjs import http from 'node:http'; // Create a local server to receive data from const server = http.createServer(); // Listen to the request event server.on('request', (request, res) => { res.writeHead(200, { 'Content-Type': 'application/json' }); res.end(JSON.stringify({ data: 'Hello World!', })); }); server.listen(8000); ``` ```cjs | https://github.com/nodejs/node/blob/main//doc/api/http.md | main | nodejs | [
-0.06502724438905716,
0.05707081779837608,
-0.01641516387462616,
0.015810947865247726,
-0.013518202118575573,
-0.0686262920498848,
0.056777555495500565,
-0.058161813765764236,
0.0379265621304512,
-0.006640219129621983,
-0.016578305512666702,
-0.018336942419409752,
0.07276971638202667,
0.01... | -0.007929 |
data: 'Hello World!', })); }); server.listen(8000); ``` ```mjs import http from 'node:http'; // Create a local server to receive data from const server = http.createServer(); // Listen to the request event server.on('request', (request, res) => { res.writeHead(200, { 'Content-Type': 'application/json' }); res.end(JSON.stringify({ data: 'Hello World!', })); }); server.listen(8000); ``` ```cjs const http = require('node:http'); // Create a local server to receive data from const server = http.createServer(); // Listen to the request event server.on('request', (request, res) => { res.writeHead(200, { 'Content-Type': 'application/json' }); res.end(JSON.stringify({ data: 'Hello World!', })); }); server.listen(8000); ``` ## `http.get(options[, callback])` ## `http.get(url[, options][, callback])` \* `url` {string | URL} \* `options` {Object} Accepts the same `options` as [`http.request()`][], with the method set to GET by default. \* `callback` {Function} \* Returns: {http.ClientRequest} Since most requests are GET requests without bodies, Node.js provides this convenience method. The only difference between this method and [`http.request()`][] is that it sets the method to GET by default and calls `req.end()` automatically. The callback must take care to consume the response data for reasons stated in [`http.ClientRequest`][] section. The `callback` is invoked with a single argument that is an instance of [`http.IncomingMessage`][]. JSON fetching example: ```js http.get('http://localhost:8000/', (res) => { const { statusCode } = res; const contentType = res.headers['content-type']; let error; // Any 2xx status code signals a successful response but // here we're only checking for 200. if (statusCode !== 200) { error = new Error('Request Failed.\n' + `Status Code: ${statusCode}`); } else if (!/^application\/json/.test(contentType)) { error = new Error('Invalid content-type.\n' + `Expected application/json but received ${contentType}`); } if (error) { console.error(error.message); // Consume response data to free up memory res.resume(); return; } res.setEncoding('utf8'); let rawData = ''; res.on('data', (chunk) => { rawData += chunk; }); res.on('end', () => { try { const parsedData = JSON.parse(rawData); console.log(parsedData); } catch (e) { console.error(e.message); } }); }).on('error', (e) => { console.error(`Got error: ${e.message}`); }); // Create a local server to receive data from const server = http.createServer((req, res) => { res.writeHead(200, { 'Content-Type': 'application/json' }); res.end(JSON.stringify({ data: 'Hello World!', })); }); server.listen(8000); ``` ## `http.globalAgent` \* Type: {http.Agent} Global instance of `Agent` which is used as the default for all HTTP client requests. Diverges from a default `Agent` configuration by having `keepAlive` enabled and a `timeout` of 5 seconds. ## `http.maxHeaderSize` \* Type: {number} Read-only property specifying the maximum allowed size of HTTP headers in bytes. Defaults to 16 KiB. Configurable using the [`--max-http-header-size`][] CLI option. This can be overridden for servers and client requests by passing the `maxHeaderSize` option. ## `http.request(options[, callback])` ## `http.request(url[, options][, callback])` \* `url` {string | URL} \* `options` {Object} \* `agent` {http.Agent | boolean} Controls [`Agent`][] behavior. Possible values: \* `undefined` (default): use [`http.globalAgent`][] for this host and port. \* `Agent` object: explicitly use the passed in `Agent`. \* `false`: causes a new `Agent` with default values to be used. \* `auth` {string} Basic authentication (`'user:password'`) to compute an Authorization header. \* `createConnection` {Function} A function that produces a socket/stream to use for the request when the `agent` option is not used. This can be used to avoid creating a custom `Agent` class just to override the default `createConnection` function. See [`agent.createConnection()`][] for more details. Any [`Duplex`][] stream is a valid return value. \* `defaultPort` {number} Default port for the protocol. \*\*Default:\*\* `agent.defaultPort` if an `Agent` is used, else `undefined`. \* `family` {number} IP address family to use when resolving `host` or `hostname`. Valid values are `4` or `6`. When unspecified, both IP v4 and v6 will be used. \* `headers` {Object|Array} An object or an array of strings containing request headers. The array is | https://github.com/nodejs/node/blob/main//doc/api/http.md | main | nodejs | [
-0.025879984721541405,
0.06000233069062233,
0.009983363561332226,
-0.03341624140739441,
-0.056936152279376984,
-0.09714991599321365,
-0.06395027041435242,
0.06519007682800293,
0.035529110580682755,
-0.016867224127054214,
-0.023857347667217255,
-0.02878112718462944,
-0.027194378897547722,
-... | 0.04872 |
`Agent` is used, else `undefined`. \* `family` {number} IP address family to use when resolving `host` or `hostname`. Valid values are `4` or `6`. When unspecified, both IP v4 and v6 will be used. \* `headers` {Object|Array} An object or an array of strings containing request headers. The array is in the same format as [`message.rawHeaders`][]. \* `hints` {number} Optional [`dns.lookup()` hints][]. \* `host` {string} A domain name or IP address of the server to issue the request to. \*\*Default:\*\* `'localhost'`. \* `hostname` {string} Alias for `host`. To support [`url.parse()`][], `hostname` will be used if both `host` and `hostname` are specified. \* `insecureHTTPParser` {boolean} If set to `true`, it will use a HTTP parser with leniency flags enabled. Using the insecure parser should be avoided. See [`--insecure-http-parser`][] for more information. \*\*Default:\*\* `false` \* `joinDuplicateHeaders` {boolean} It joins the field line values of multiple headers in a request with `, ` instead of discarding the duplicates. See [`message.headers`][] for more information. \*\*Default:\*\* `false`. \* `localAddress` {string} Local interface to bind for network connections. \* `localPort` {number} Local port to connect from. \* `lookup` {Function} Custom lookup function. \*\*Default:\*\* [`dns.lookup()`][]. \* `maxHeaderSize` {number} Optionally overrides the value of [`--max-http-header-size`][] (the maximum length of response headers in bytes) for responses received from the server. \*\*Default:\*\* 16384 (16 KiB). \* `method` {string} A string specifying the HTTP request method. \*\*Default:\*\* `'GET'`. \* `path` {string} Request path. Should include query string if any. E.G. `'/index.html?page=12'`. An exception is thrown when the request path contains illegal characters. Currently, only spaces are rejected but that may change in the future. \*\*Default:\*\* `'/'`. \* `port` {number} Port of remote server. \*\*Default:\*\* `defaultPort` if set, else `80`. \* `protocol` {string} Protocol to use. \*\*Default:\*\* `'http:'`. \* `setDefaultHeaders` {boolean}: Specifies whether or not to automatically add default headers such as `Connection`, `Content-Length`, `Transfer-Encoding`, and `Host`. If set to `false` then all necessary headers must be added manually. Defaults to `true`. \* `setHost` {boolean}: Specifies whether or not to automatically add the `Host` header. If provided, this overrides `setDefaultHeaders`. Defaults to `true`. \* `signal` {AbortSignal}: An AbortSignal that may be used to abort an ongoing request. \* `socketPath` {string} Unix domain socket. Cannot be used if one of `host` or `port` is specified, as those specify a TCP Socket. \* `timeout` {number}: A number specifying the socket timeout in milliseconds. This will set the timeout before the socket is connected. \* `uniqueHeaders` {Array} A list of request headers that should be sent only once. If the header's value is an array, the items will be joined using `; `. \* `callback` {Function} \* Returns: {http.ClientRequest} `options` in [`socket.connect()`][] are also supported. Node.js maintains several connections per server to make HTTP requests. This function allows one to transparently issue requests. `url` can be a string or a [`URL`][] object. If `url` is a string, it is automatically parsed with [`new URL()`][]. If it is a [`URL`][] object, it will be automatically converted to an ordinary `options` object. If both `url` and `options` are specified, the objects are merged, with the `options` properties taking precedence. The optional `callback` parameter will be added as a one-time listener for the [`'response'`][] event. `http.request()` returns an instance of the [`http.ClientRequest`][] class. The `ClientRequest` instance is a writable stream. If one needs to upload a file with a POST request, then write to the `ClientRequest` object. ```mjs import http from 'node:http'; import { Buffer } from 'node:buffer'; const postData = JSON.stringify({ 'msg': 'Hello World!', }); const options = { hostname: 'www.google.com', port: 80, path: '/upload', method: 'POST', headers: { 'Content-Type': 'application/json', 'Content-Length': Buffer.byteLength(postData), }, }; const req | https://github.com/nodejs/node/blob/main//doc/api/http.md | main | nodejs | [
-0.053959690034389496,
0.05684254691004753,
-0.035657353699207306,
-0.045545544475317,
-0.045701056718826294,
-0.09495113044977188,
-0.026552913710474968,
-0.020825976505875587,
-0.015925854444503784,
-0.04351024702191353,
-0.02751701883971691,
-0.04888898506760597,
0.04299357905983925,
-0... | 0.054527 |
a POST request, then write to the `ClientRequest` object. ```mjs import http from 'node:http'; import { Buffer } from 'node:buffer'; const postData = JSON.stringify({ 'msg': 'Hello World!', }); const options = { hostname: 'www.google.com', port: 80, path: '/upload', method: 'POST', headers: { 'Content-Type': 'application/json', 'Content-Length': Buffer.byteLength(postData), }, }; const req = http.request(options, (res) => { console.log(`STATUS: ${res.statusCode}`); console.log(`HEADERS: ${JSON.stringify(res.headers)}`); res.setEncoding('utf8'); res.on('data', (chunk) => { console.log(`BODY: ${chunk}`); }); res.on('end', () => { console.log('No more data in response.'); }); }); req.on('error', (e) => { console.error(`problem with request: ${e.message}`); }); // Write data to request body req.write(postData); req.end(); ``` ```cjs const http = require('node:http'); const postData = JSON.stringify({ 'msg': 'Hello World!', }); const options = { hostname: 'www.google.com', port: 80, path: '/upload', method: 'POST', headers: { 'Content-Type': 'application/json', 'Content-Length': Buffer.byteLength(postData), }, }; const req = http.request(options, (res) => { console.log(`STATUS: ${res.statusCode}`); console.log(`HEADERS: ${JSON.stringify(res.headers)}`); res.setEncoding('utf8'); res.on('data', (chunk) => { console.log(`BODY: ${chunk}`); }); res.on('end', () => { console.log('No more data in response.'); }); }); req.on('error', (e) => { console.error(`problem with request: ${e.message}`); }); // Write data to request body req.write(postData); req.end(); ``` In the example `req.end()` was called. With `http.request()` one must always call `req.end()` to signify the end of the request - even if there is no data being written to the request body. If any error is encountered during the request (be that with DNS resolution, TCP level errors, or actual HTTP parse errors) an `'error'` event is emitted on the returned request object. As with all `'error'` events, if no listeners are registered the error will be thrown. There are a few special headers that should be noted. \* Sending a 'Connection: keep-alive' will notify Node.js that the connection to the server should be persisted until the next request. \* Sending a 'Content-Length' header will disable the default chunked encoding. \* Sending an 'Expect' header will immediately send the request headers. Usually, when sending 'Expect: 100-continue', both a timeout and a listener for the `'continue'` event should be set. See RFC 2616 Section 8.2.3 for more information. \* Sending an Authorization header will override using the `auth` option to compute basic authentication. Example using a [`URL`][] as `options`: ```js const options = new URL('http://abc:xyz@example.com'); const req = http.request(options, (res) => { // ... }); ``` In a successful request, the following events will be emitted in the following order: \* `'socket'` \* `'response'` \* `'data'` any number of times, on the `res` object (`'data'` will not be emitted at all if the response body is empty, for instance, in most redirects) \* `'end'` on the `res` object \* `'close'` In the case of a connection error, the following events will be emitted: \* `'socket'` \* `'error'` \* `'close'` In the case of a premature connection close before the response is received, the following events will be emitted in the following order: \* `'socket'` \* `'error'` with an error with message `'Error: socket hang up'` and code `'ECONNRESET'` \* `'close'` In the case of a premature connection close after the response is received, the following events will be emitted in the following order: \* `'socket'` \* `'response'` \* `'data'` any number of times, on the `res` object \* (connection closed here) \* `'aborted'` on the `res` object \* `'close'` \* `'error'` on the `res` object with an error with message `'Error: aborted'` and code `'ECONNRESET'` \* `'close'` on the `res` object If `req.destroy()` is called before a socket is assigned, the following events will be emitted in the following order: \* (`req.destroy()` called here) \* `'error'` with an error with message `'Error: socket hang up'` and code `'ECONNRESET'`, or the error with which | https://github.com/nodejs/node/blob/main//doc/api/http.md | main | nodejs | [
-0.039562445133924484,
0.05934811010956764,
0.013661990873515606,
-0.00960452202707529,
-0.04119473323225975,
-0.09106060117483139,
-0.07072456181049347,
0.0711643174290657,
0.0041894991882145405,
0.05436104163527489,
-0.03367387130856514,
0.03918299078941345,
0.00457236310467124,
-0.02278... | 0.012502 |
code `'ECONNRESET'` \* `'close'` on the `res` object If `req.destroy()` is called before a socket is assigned, the following events will be emitted in the following order: \* (`req.destroy()` called here) \* `'error'` with an error with message `'Error: socket hang up'` and code `'ECONNRESET'`, or the error with which `req.destroy()` was called \* `'close'` If `req.destroy()` is called before the connection succeeds, the following events will be emitted in the following order: \* `'socket'` \* (`req.destroy()` called here) \* `'error'` with an error with message `'Error: socket hang up'` and code `'ECONNRESET'`, or the error with which `req.destroy()` was called \* `'close'` If `req.destroy()` is called after the response is received, the following events will be emitted in the following order: \* `'socket'` \* `'response'` \* `'data'` any number of times, on the `res` object \* (`req.destroy()` called here) \* `'aborted'` on the `res` object \* `'close'` \* `'error'` on the `res` object with an error with message `'Error: aborted'` and code `'ECONNRESET'`, or the error with which `req.destroy()` was called \* `'close'` on the `res` object If `req.abort()` is called before a socket is assigned, the following events will be emitted in the following order: \* (`req.abort()` called here) \* `'abort'` \* `'close'` If `req.abort()` is called before the connection succeeds, the following events will be emitted in the following order: \* `'socket'` \* (`req.abort()` called here) \* `'abort'` \* `'error'` with an error with message `'Error: socket hang up'` and code `'ECONNRESET'` \* `'close'` If `req.abort()` is called after the response is received, the following events will be emitted in the following order: \* `'socket'` \* `'response'` \* `'data'` any number of times, on the `res` object \* (`req.abort()` called here) \* `'abort'` \* `'aborted'` on the `res` object \* `'error'` on the `res` object with an error with message `'Error: aborted'` and code `'ECONNRESET'`. \* `'close'` \* `'close'` on the `res` object Setting the `timeout` option or using the `setTimeout()` function will not abort the request or do anything besides add a `'timeout'` event. Passing an `AbortSignal` and then calling `abort()` on the corresponding `AbortController` will behave the same way as calling `.destroy()` on the request. Specifically, the `'error'` event will be emitted with an error with the message `'AbortError: The operation was aborted'`, the code `'ABORT\_ERR'` and the `cause`, if one was provided. ## `http.validateHeaderName(name[, label])` \* `name` {string} \* `label` {string} Label for error message. \*\*Default:\*\* `'Header name'`. Performs the low-level validations on the provided `name` that are done when `res.setHeader(name, value)` is called. Passing illegal value as `name` will result in a [`TypeError`][] being thrown, identified by `code: 'ERR\_INVALID\_HTTP\_TOKEN'`. It is not necessary to use this method before passing headers to an HTTP request or response. The HTTP module will automatically validate such headers. Example: ```mjs import { validateHeaderName } from 'node:http'; try { validateHeaderName(''); } catch (err) { console.error(err instanceof TypeError); // --> true console.error(err.code); // --> 'ERR\_INVALID\_HTTP\_TOKEN' console.error(err.message); // --> 'Header name must be a valid HTTP token [""]' } ``` ```cjs const { validateHeaderName } = require('node:http'); try { validateHeaderName(''); } catch (err) { console.error(err instanceof TypeError); // --> true console.error(err.code); // --> 'ERR\_INVALID\_HTTP\_TOKEN' console.error(err.message); // --> 'Header name must be a valid HTTP token [""]' } ``` ## `http.validateHeaderValue(name, value)` \* `name` {string} \* `value` {any} Performs the low-level validations on the provided `value` that are done when `res.setHeader(name, value)` is called. Passing illegal value as `value` will result in a [`TypeError`][] being thrown. \* Undefined value error is identified by `code: 'ERR\_HTTP\_INVALID\_HEADER\_VALUE'`. \* Invalid value character error is identified by `code: 'ERR\_INVALID\_CHAR'`. It is not necessary to use | https://github.com/nodejs/node/blob/main//doc/api/http.md | main | nodejs | [
-0.07541520148515701,
0.003622199408710003,
0.007341453339904547,
0.05325992405414581,
-0.02123754657804966,
-0.06106157228350639,
0.021833287551999092,
-0.009026702493429184,
0.11857949197292328,
0.02639152482151985,
0.01006031408905983,
-0.002227058866992593,
-0.043436188250780106,
0.022... | 0.109991 |
validations on the provided `value` that are done when `res.setHeader(name, value)` is called. Passing illegal value as `value` will result in a [`TypeError`][] being thrown. \* Undefined value error is identified by `code: 'ERR\_HTTP\_INVALID\_HEADER\_VALUE'`. \* Invalid value character error is identified by `code: 'ERR\_INVALID\_CHAR'`. It is not necessary to use this method before passing headers to an HTTP request or response. The HTTP module will automatically validate such headers. Examples: ```mjs import { validateHeaderValue } from 'node:http'; try { validateHeaderValue('x-my-header', undefined); } catch (err) { console.error(err instanceof TypeError); // --> true console.error(err.code === 'ERR\_HTTP\_INVALID\_HEADER\_VALUE'); // --> true console.error(err.message); // --> 'Invalid value "undefined" for header "x-my-header"' } try { validateHeaderValue('x-my-header', 'oʊmɪɡə'); } catch (err) { console.error(err instanceof TypeError); // --> true console.error(err.code === 'ERR\_INVALID\_CHAR'); // --> true console.error(err.message); // --> 'Invalid character in header content ["x-my-header"]' } ``` ```cjs const { validateHeaderValue } = require('node:http'); try { validateHeaderValue('x-my-header', undefined); } catch (err) { console.error(err instanceof TypeError); // --> true console.error(err.code === 'ERR\_HTTP\_INVALID\_HEADER\_VALUE'); // --> true console.error(err.message); // --> 'Invalid value "undefined" for header "x-my-header"' } try { validateHeaderValue('x-my-header', 'oʊmɪɡə'); } catch (err) { console.error(err instanceof TypeError); // --> true console.error(err.code === 'ERR\_INVALID\_CHAR'); // --> true console.error(err.message); // --> 'Invalid character in header content ["x-my-header"]' } ``` ## `http.setMaxIdleHTTPParsers(max)` \* `max` {number} \*\*Default:\*\* `1000`. Set the maximum number of idle HTTP parsers. ## `http.setGlobalProxyFromEnv([proxyEnv])` \* `proxyEnv` {Object} An object containing proxy configuration. This accepts the same options as the `proxyEnv` option accepted by [`Agent`][]. \*\*Default:\*\* `process.env`. \* Returns: {Function} A function that restores the original agent and dispatcher settings to the state before this `http.setGlobalProxyFromEnv()` is invoked. Dynamically resets the global configurations to enable built-in proxy support for `fetch()` and `http.request()`/`https.request()` at runtime, as an alternative to using the `--use-env-proxy` flag or `NODE\_USE\_ENV\_PROXY` environment variable. It can also be used to override settings configured from the environment variables. As this function resets the global configurations, any previously configured `http.globalAgent`, `https.globalAgent` or undici global dispatcher would be overridden after this function is invoked. It's recommended to invoke it before any requests are made and avoid invoking it in the middle of any requests. See [Built-in Proxy Support][] for details on proxy URL formats and `NO\_PROXY` syntax. ## Class: `WebSocket` A browser-compatible implementation of {WebSocket}. ## Built-in Proxy Support > Stability: 1.1 - Active development When Node.js creates the global agent, if the `NODE\_USE\_ENV\_PROXY` environment variable is set to `1` or `--use-env-proxy` is enabled, the global agent will be constructed with `proxyEnv: process.env`, enabling proxy support based on the environment variables. To enable proxy support dynamically and globally, use [`http.setGlobalProxyFromEnv()`][]. Custom agents can also be created with proxy support by passing a `proxyEnv` option when constructing the agent. The value can be `process.env` if they just want to inherit the configuration from the environment variables, or an object with specific setting overriding the environment. The following properties of the `proxyEnv` are checked to configure proxy support. \* `HTTP\_PROXY` or `http\_proxy`: Proxy server URL for HTTP requests. If both are set, `http\_proxy` takes precedence. \* `HTTPS\_PROXY` or `https\_proxy`: Proxy server URL for HTTPS requests. If both are set, `https\_proxy` takes precedence. \* `NO\_PROXY` or `no\_proxy`: Comma-separated list of hosts to bypass the proxy. If both are set, `no\_proxy` takes precedence. If the request is made to a Unix domain socket, the proxy settings will be ignored. ### Proxy URL Format Proxy URLs can use either HTTP or HTTPS protocols: \* HTTP proxy: `http://proxy.example.com:8080` \* HTTPS proxy: `https://proxy.example.com:8080` \* Proxy with authentication: `http://username:password@proxy.example.com:8080` ### `NO\_PROXY` Format The `NO\_PROXY` environment variable supports several formats: \* `\*` - Bypass proxy for all hosts \* `example.com` - Exact | https://github.com/nodejs/node/blob/main//doc/api/http.md | main | nodejs | [
-0.09003995358943939,
0.13565047085285187,
0.02096158266067505,
-0.02850329503417015,
0.026540735736489296,
-0.02636636234819889,
-0.015550854615867138,
0.07713967561721802,
0.028539929538965225,
-0.010663798078894615,
-0.06330537050962448,
-0.06706901639699936,
0.0644676610827446,
0.04014... | 0.032297 |
be ignored. ### Proxy URL Format Proxy URLs can use either HTTP or HTTPS protocols: \* HTTP proxy: `http://proxy.example.com:8080` \* HTTPS proxy: `https://proxy.example.com:8080` \* Proxy with authentication: `http://username:password@proxy.example.com:8080` ### `NO\_PROXY` Format The `NO\_PROXY` environment variable supports several formats: \* `\*` - Bypass proxy for all hosts \* `example.com` - Exact host name match \* `.example.com` - Domain suffix match (matches `sub.example.com`) \* `\*.example.com` - Wildcard domain match \* `192.168.1.100` - Exact IP address match \* `192.168.1.1-192.168.1.100` - IP address range \* `example.com:8080` - Hostname with specific port Multiple entries should be separated by commas. ### Example To start a Node.js process with proxy support enabled for all requests sent through the default global agent, either use the `NODE\_USE\_ENV\_PROXY` environment variable: ```console NODE\_USE\_ENV\_PROXY=1 HTTP\_PROXY=http://proxy.example.com:8080 NO\_PROXY=localhost,127.0.0.1 node client.js ``` Or the `--use-env-proxy` flag. ```console HTTP\_PROXY=http://proxy.example.com:8080 NO\_PROXY=localhost,127.0.0.1 node --use-env-proxy client.js ``` To enable proxy support dynamically and globally with `process.env` (the default option of `http.setGlobalProxyFromEnv()`): ```cjs const http = require('node:http'); // Reads proxy-related environment variables from process.env const restore = http.setGlobalProxyFromEnv(); // Subsequent requests will use the configured proxies from environment variables http.get('http://www.example.com', (res) => { // This request will be proxied if HTTP\_PROXY or http\_proxy is set }); fetch('https://www.example.com', (res) => { // This request will be proxied if HTTPS\_PROXY or https\_proxy is set }); // To restore the original global agent and dispatcher settings, call the returned function. // restore(); ``` ```mjs import http from 'node:http'; // Reads proxy-related environment variables from process.env http.setGlobalProxyFromEnv(); // Subsequent requests will use the configured proxies from environment variables http.get('http://www.example.com', (res) => { // This request will be proxied if HTTP\_PROXY or http\_proxy is set }); fetch('https://www.example.com', (res) => { // This request will be proxied if HTTPS\_PROXY or https\_proxy is set }); // To restore the original global agent and dispatcher settings, call the returned function. // restore(); ``` To enable proxy support dynamically and globally with custom settings: ```cjs const http = require('node:http'); const restore = http.setGlobalProxyFromEnv({ http\_proxy: 'http://proxy.example.com:8080', https\_proxy: 'https://proxy.example.com:8443', no\_proxy: 'localhost,127.0.0.1,.internal.example.com', }); // Subsequent requests will use the configured proxies http.get('http://www.example.com', (res) => { // This request will be proxied through proxy.example.com:8080 }); fetch('https://www.example.com', (res) => { // This request will be proxied through proxy.example.com:8443 }); ``` ```mjs import http from 'node:http'; http.setGlobalProxyFromEnv({ http\_proxy: 'http://proxy.example.com:8080', https\_proxy: 'https://proxy.example.com:8443', no\_proxy: 'localhost,127.0.0.1,.internal.example.com', }); // Subsequent requests will use the configured proxies http.get('http://www.example.com', (res) => { // This request will be proxied through proxy.example.com:8080 }); fetch('https://www.example.com', (res) => { // This request will be proxied through proxy.example.com:8443 }); ``` To create a custom agent with built-in proxy support: ```cjs const http = require('node:http'); // Creating a custom agent with custom proxy support. const agent = new http.Agent({ proxyEnv: { HTTP\_PROXY: 'http://proxy.example.com:8080' } }); http.request({ hostname: 'www.example.com', port: 80, path: '/', agent, }, (res) => { // This request will be proxied through proxy.example.com:8080 using the HTTP protocol. console.log(`STATUS: ${res.statusCode}`); }); ``` Alternatively, the following also works: ```cjs const http = require('node:http'); // Use lower-cased option name. const agent1 = new http.Agent({ proxyEnv: { http\_proxy: 'http://proxy.example.com:8080' } }); // Use values inherited from the environment variables, if the process is started with // HTTP\_PROXY=http://proxy.example.com:8080 this will use the proxy server specified // in process.env.HTTP\_PROXY. const agent2 = new http.Agent({ proxyEnv: process.env }); ``` [Built-in Proxy Support]: #built-in-proxy-support [RFC 8187]: https://www.rfc-editor.org/rfc/rfc8187.txt [`'ERR\_HTTP\_CONTENT\_LENGTH\_MISMATCH'`]: errors.md#err\_http\_content\_length\_mismatch [`'checkContinue'`]: #event-checkcontinue [`'finish'`]: #event-finish [`'request'`]: #event-request [`'response'`]: #event-response [`'upgrade'`]: #event-upgrade [`--insecure-http-parser`]: cli.md#--insecure-http-parser [`--max-http-header-size`]: cli.md#--max-http-header-sizesize [`Agent`]: #class-httpagent [`Buffer.byteLength()`]: buffer.md#static-method-bufferbytelengthstring-encoding [`Duplex`]: stream.md#class-streamduplex [`HPE\_HEADER\_OVERFLOW`]: errors.md#hpe\_header\_overflow [`Headers`]: globals.md#class-headers [`TypeError`]: errors.md#class-typeerror [`URL`]: url.md#the-whatwg-url-api [`agent.createConnection()`]: #agentcreateconnectionoptions-callback [`agent.getName()`]: #agentgetnameoptions [`destroy()`]: #agentdestroy [`dns.lookup()`]: dns.md#dnslookuphostname-options-callback [`dns.lookup()` hints]: dns.md#supported-getaddrinfo-flags [`getHeader(name)`]: #requestgetheadername [`http.Agent`]: #class-httpagent [`http.ClientRequest`]: #class-httpclientrequest [`http.IncomingMessage`]: #class-httpincomingmessage [`http.ServerResponse`]: #class-httpserverresponse [`http.Server`]: #class-httpserver [`http.createServer()`]: #httpcreateserveroptions-requestlistener [`http.get()`]: | https://github.com/nodejs/node/blob/main//doc/api/http.md | main | nodejs | [
-0.06141340732574463,
0.041854213923215866,
0.026151718571782112,
-0.06707572937011719,
-0.03264071047306061,
-0.09750188887119293,
-0.03352542221546173,
-0.01451609656214714,
-0.019276270642876625,
0.04362490400671959,
-0.07859257608652115,
0.04127925634384155,
0.030605990439653397,
0.028... | -0.052487 |
[`'request'`]: #event-request [`'response'`]: #event-response [`'upgrade'`]: #event-upgrade [`--insecure-http-parser`]: cli.md#--insecure-http-parser [`--max-http-header-size`]: cli.md#--max-http-header-sizesize [`Agent`]: #class-httpagent [`Buffer.byteLength()`]: buffer.md#static-method-bufferbytelengthstring-encoding [`Duplex`]: stream.md#class-streamduplex [`HPE\_HEADER\_OVERFLOW`]: errors.md#hpe\_header\_overflow [`Headers`]: globals.md#class-headers [`TypeError`]: errors.md#class-typeerror [`URL`]: url.md#the-whatwg-url-api [`agent.createConnection()`]: #agentcreateconnectionoptions-callback [`agent.getName()`]: #agentgetnameoptions [`destroy()`]: #agentdestroy [`dns.lookup()`]: dns.md#dnslookuphostname-options-callback [`dns.lookup()` hints]: dns.md#supported-getaddrinfo-flags [`getHeader(name)`]: #requestgetheadername [`http.Agent`]: #class-httpagent [`http.ClientRequest`]: #class-httpclientrequest [`http.IncomingMessage`]: #class-httpincomingmessage [`http.ServerResponse`]: #class-httpserverresponse [`http.Server`]: #class-httpserver [`http.createServer()`]: #httpcreateserveroptions-requestlistener [`http.get()`]: #httpgetoptions-callback [`http.globalAgent`]: #httpglobalagent [`http.request()`]: #httprequestoptions-callback [`http.setGlobalProxyFromEnv()`]: #httpsetglobalproxyfromenvproxyenv [`message.headers`]: #messageheaders [`message.rawHeaders`]: #messagerawheaders [`message.socket`]: #messagesocket [`message.trailers`]: #messagetrailers [`net.Server.close()`]: net.md#serverclosecallback [`net.Server`]: net.md#class-netserver [`net.Socket`]: net.md#class-netsocket [`net.createConnection()`]: net.md#netcreateconnectionoptions-connectlistener [`new URL()`]: url.md#new-urlinput-base [`outgoingMessage.setHeader(name, value)`]: #outgoingmessagesetheadername-value [`outgoingMessage.setHeaders()`]: #outgoingmessagesetheadersheaders [`outgoingMessage.socket`]: #outgoingmessagesocket [`removeHeader(name)`]: #requestremoveheadername [`request.destroy()`]: #requestdestroyerror [`request.destroyed`]: #requestdestroyed [`request.end()`]: #requestenddata-encoding-callback [`request.flushHeaders()`]: #requestflushheaders [`request.getHeader()`]: #requestgetheadername [`request.setHeader()`]: #requestsetheadername-value [`request.setTimeout()`]: #requestsettimeouttimeout-callback [`request.socket.getPeerCertificate()`]: tls.md#tlssocketgetpeercertificatedetailed [`request.socket`]: #requestsocket [`request.writableEnded`]: #requestwritableended [`request.writableFinished`]: #requestwritablefinished [`request.write(data, encoding)`]: #requestwritechunk-encoding-callback [`response.end()`]: #responseenddata-encoding-callback [`response.getHeader()`]: #responsegetheadername [`response.setHeader()`]: #responsesetheadername-value [`response.socket`]: #responsesocket [`response.strictContentLength`]: #responsestrictcontentlength [`response.writableEnded`]: #responsewritableended [`response.writableFinished`]: #responsewritablefinished [`response.write()`]: #responsewritechunk-encoding-callback [`response.write(data, encoding)`]: #responsewritechunk-encoding-callback [`response.writeContinue()`]: #responsewritecontinue [`response.writeHead()`]: #responsewriteheadstatuscode-statusmessage-headers [`server.close()`]: #serverclosecallback [`server.headersTimeout`]: #serverheaderstimeout [`server.keepAliveTimeoutBuffer`]: #serverkeepalivetimeoutbuffer [`server.keepAliveTimeout`]: #serverkeepalivetimeout [`server.listen()`]: net.md#serverlisten [`server.requestTimeout`]: #serverrequesttimeout [`server.timeout`]: #servertimeout [`setHeader(name, value)`]: #requestsetheadername-value [`socket.connect()`]: net.md#socketconnectoptions-connectlistener [`socket.setKeepAlive()`]: net.md#socketsetkeepaliveenable-initialdelay [`socket.setNoDelay()`]: net.md#socketsetnodelaynodelay [`socket.setTimeout()`]: net.md#socketsettimeouttimeout-callback [`socket.unref()`]: net.md#socketunref [`stream.getDefaultHighWaterMark()`]: stream.md#streamgetdefaulthighwatermarkobjectmode [`url.parse()`]: url.md#urlparseurlstring-parsequerystring-slashesdenotehost [`writable.cork()`]: stream.md#writablecork [`writable.destroy()`]: stream.md#writabledestroyerror [`writable.destroyed`]: stream.md#writabledestroyed [`writable.uncork()`]: stream.md#writableuncork [`writable.write()`]: stream.md#writablewritechunk-encoding-callback [initial delay]: net.md#socketsetkeepaliveenable-initialdelay | https://github.com/nodejs/node/blob/main//doc/api/http.md | main | nodejs | [
-0.006177391856908798,
0.08713795989751816,
-0.06537745893001556,
-0.0952792689204216,
-0.011615725234150887,
-0.10587483644485474,
-0.06755749881267548,
0.01718883588910103,
-0.04120954871177673,
-0.001211198978126049,
-0.01812298223376274,
-0.03865402191877365,
-0.02124895714223385,
-0.0... | -0.038023 |
# File system > Stability: 2 - Stable The `node:fs` module enables interacting with the file system in a way modeled on standard POSIX functions. To use the promise-based APIs: ```mjs import \* as fs from 'node:fs/promises'; ``` ```cjs const fs = require('node:fs/promises'); ``` To use the callback and sync APIs: ```mjs import \* as fs from 'node:fs'; ``` ```cjs const fs = require('node:fs'); ``` All file system operations have synchronous, callback, and promise-based forms, and are accessible using both CommonJS syntax and ES6 Modules (ESM). ## Promise example Promise-based operations return a promise that is fulfilled when the asynchronous operation is complete. ```mjs import { unlink } from 'node:fs/promises'; try { await unlink('/tmp/hello'); console.log('successfully deleted /tmp/hello'); } catch (error) { console.error('there was an error:', error.message); } ``` ```cjs const { unlink } = require('node:fs/promises'); (async function(path) { try { await unlink(path); console.log(`successfully deleted ${path}`); } catch (error) { console.error('there was an error:', error.message); } })('/tmp/hello'); ``` ## Callback example The callback form takes a completion callback function as its last argument and invokes the operation asynchronously. The arguments passed to the completion callback depend on the method, but the first argument is always reserved for an exception. If the operation is completed successfully, then the first argument is `null` or `undefined`. ```mjs import { unlink } from 'node:fs'; unlink('/tmp/hello', (err) => { if (err) throw err; console.log('successfully deleted /tmp/hello'); }); ``` ```cjs const { unlink } = require('node:fs'); unlink('/tmp/hello', (err) => { if (err) throw err; console.log('successfully deleted /tmp/hello'); }); ``` The callback-based versions of the `node:fs` module APIs are preferable over the use of the promise APIs when maximal performance (both in terms of execution time and memory allocation) is required. ## Synchronous example The synchronous APIs block the Node.js event loop and further JavaScript execution until the operation is complete. Exceptions are thrown immediately and can be handled using `try…catch`, or can be allowed to bubble up. ```mjs import { unlinkSync } from 'node:fs'; try { unlinkSync('/tmp/hello'); console.log('successfully deleted /tmp/hello'); } catch (err) { // handle the error } ``` ```cjs const { unlinkSync } = require('node:fs'); try { unlinkSync('/tmp/hello'); console.log('successfully deleted /tmp/hello'); } catch (err) { // handle the error } ``` ## Promises API The `fs/promises` API provides asynchronous file system methods that return promises. The promise APIs use the underlying Node.js threadpool to perform file system operations off the event loop thread. These operations are not synchronized or threadsafe. Care must be taken when performing multiple concurrent modifications on the same file or data corruption may occur. ### Class: `FileHandle` A {FileHandle} object is an object wrapper for a numeric file descriptor. Instances of the {FileHandle} object are created by the `fsPromises.open()` method. All {FileHandle} objects are {EventEmitter}s. If a {FileHandle} is not closed using the `filehandle.close()` method, it will try to automatically close the file descriptor and emit a process warning, helping to prevent memory leaks. Please do not rely on this behavior because it can be unreliable and the file may not be closed. Instead, always explicitly close {FileHandle}s. Node.js may change this behavior in the future. #### Event: `'close'` The `'close'` event is emitted when the {FileHandle} has been closed and can no longer be used. #### `filehandle.appendFile(data[, options])` \* `data` {string|Buffer|TypedArray|DataView|AsyncIterable|Iterable|Stream} \* `options` {Object|string} \* `encoding` {string|null} \*\*Default:\*\* `'utf8'` \* `signal` {AbortSignal|undefined} allows aborting an in-progress writeFile. \*\*Default:\*\* `undefined` \* Returns: {Promise} Fulfills with `undefined` upon success. Alias of [`filehandle.writeFile()`][]. When operating on file handles, the mode cannot be changed from what it was set to with [`fsPromises.open()`][]. Therefore, this is equivalent to [`filehandle.writeFile()`][]. #### `filehandle.chmod(mode)` \* `mode` {integer} the | https://github.com/nodejs/node/blob/main//doc/api/fs.md | main | nodejs | [
-0.15448524057865143,
0.025174366310238838,
-0.03009718470275402,
0.058856893330812454,
0.05172360688447952,
-0.06640716642141342,
-0.04353522136807442,
0.11084537953138351,
0.08615563809871674,
0.022520318627357483,
-0.00513014430180192,
0.1023981049656868,
-0.01369669009000063,
-0.028897... | 0.207335 |
`signal` {AbortSignal|undefined} allows aborting an in-progress writeFile. \*\*Default:\*\* `undefined` \* Returns: {Promise} Fulfills with `undefined` upon success. Alias of [`filehandle.writeFile()`][]. When operating on file handles, the mode cannot be changed from what it was set to with [`fsPromises.open()`][]. Therefore, this is equivalent to [`filehandle.writeFile()`][]. #### `filehandle.chmod(mode)` \* `mode` {integer} the file mode bit mask. \* Returns: {Promise} Fulfills with `undefined` upon success. Modifies the permissions on the file. See chmod(2). #### `filehandle.chown(uid, gid)` \* `uid` {integer} The file's new owner's user id. \* `gid` {integer} The file's new group's group id. \* Returns: {Promise} Fulfills with `undefined` upon success. Changes the ownership of the file. A wrapper for chown(2). #### `filehandle.close()` \* Returns: {Promise} Fulfills with `undefined` upon success. Closes the file handle after waiting for any pending operation on the handle to complete. ```mjs import { open } from 'node:fs/promises'; let filehandle; try { filehandle = await open('thefile.txt', 'r'); } finally { await filehandle?.close(); } ``` #### `filehandle.createReadStream([options])` \* `options` {Object} \* `encoding` {string} \*\*Default:\*\* `null` \* `autoClose` {boolean} \*\*Default:\*\* `true` \* `emitClose` {boolean} \*\*Default:\*\* `true` \* `start` {integer} \* `end` {integer} \*\*Default:\*\* `Infinity` \* `highWaterMark` {integer} \*\*Default:\*\* `64 \* 1024` \* `signal` {AbortSignal|undefined} \*\*Default:\*\* `undefined` \* Returns: {fs.ReadStream} `options` can include `start` and `end` values to read a range of bytes from the file instead of the entire file. Both `start` and `end` are inclusive and start counting at 0, allowed values are in the \[0, [`Number.MAX\_SAFE\_INTEGER`][]] range. If `start` is omitted or `undefined`, `filehandle.createReadStream()` reads sequentially from the current file position. The `encoding` can be any one of those accepted by {Buffer}. If the `FileHandle` points to a character device that only supports blocking reads (such as keyboard or sound card), read operations do not finish until data is available. This can prevent the process from exiting and the stream from closing naturally. By default, the stream will emit a `'close'` event after it has been destroyed. Set the `emitClose` option to `false` to change this behavior. ```mjs import { open } from 'node:fs/promises'; const fd = await open('/dev/input/event0'); // Create a stream from some character device. const stream = fd.createReadStream(); setTimeout(() => { stream.close(); // This may not close the stream. // Artificially marking end-of-stream, as if the underlying resource had // indicated end-of-file by itself, allows the stream to close. // This does not cancel pending read operations, and if there is such an // operation, the process may still not be able to exit successfully // until it finishes. stream.push(null); stream.read(0); }, 100); ``` If `autoClose` is false, then the file descriptor won't be closed, even if there's an error. It is the application's responsibility to close it and make sure there's no file descriptor leak. If `autoClose` is set to true (default behavior), on `'error'` or `'end'` the file descriptor will be closed automatically. An example to read the last 10 bytes of a file which is 100 bytes long: ```mjs import { open } from 'node:fs/promises'; const fd = await open('sample.txt'); fd.createReadStream({ start: 90, end: 99 }); ``` #### `filehandle.createWriteStream([options])` \* `options` {Object} \* `encoding` {string} \*\*Default:\*\* `'utf8'` \* `autoClose` {boolean} \*\*Default:\*\* `true` \* `emitClose` {boolean} \*\*Default:\*\* `true` \* `start` {integer} \* `highWaterMark` {number} \*\*Default:\*\* `16384` \* `flush` {boolean} If `true`, the underlying file descriptor is flushed prior to closing it. \*\*Default:\*\* `false`. \* Returns: {fs.WriteStream} `options` may also include a `start` option to allow writing data at some position past the beginning of the file, allowed values are in the \[0, [`Number.MAX\_SAFE\_INTEGER`][]] range. Modifying a file rather than replacing it may require the `flags` `open` option to be set to `r+` | https://github.com/nodejs/node/blob/main//doc/api/fs.md | main | nodejs | [
-0.07021939009428024,
0.02681177854537964,
-0.0067336964420974255,
0.04724578559398651,
0.029670536518096924,
-0.06783460825681686,
0.029100388288497925,
0.06669870764017105,
0.0549548864364624,
0.010445459745824337,
0.05509376525878906,
0.07472683489322662,
-0.06094291806221008,
-0.006974... | 0.144234 |
`false`. \* Returns: {fs.WriteStream} `options` may also include a `start` option to allow writing data at some position past the beginning of the file, allowed values are in the \[0, [`Number.MAX\_SAFE\_INTEGER`][]] range. Modifying a file rather than replacing it may require the `flags` `open` option to be set to `r+` rather than the default `r`. The `encoding` can be any one of those accepted by {Buffer}. If `autoClose` is set to true (default behavior) on `'error'` or `'finish'` the file descriptor will be closed automatically. If `autoClose` is false, then the file descriptor won't be closed, even if there's an error. It is the application's responsibility to close it and make sure there's no file descriptor leak. By default, the stream will emit a `'close'` event after it has been destroyed. Set the `emitClose` option to `false` to change this behavior. #### `filehandle.datasync()` \* Returns: {Promise} Fulfills with `undefined` upon success. Forces all currently queued I/O operations associated with the file to the operating system's synchronized I/O completion state. Refer to the POSIX fdatasync(2) documentation for details. Unlike `filehandle.sync` this method does not flush modified metadata. #### `filehandle.fd` \* Type: {number} The numeric file descriptor managed by the {FileHandle} object. #### `filehandle.read(buffer, offset, length, position)` \* `buffer` {Buffer|TypedArray|DataView} A buffer that will be filled with the file data read. \* `offset` {integer} The location in the buffer at which to start filling. \*\*Default:\*\* `0` \* `length` {integer} The number of bytes to read. \*\*Default:\*\* `buffer.byteLength - offset` \* `position` {integer|bigint|null} The location where to begin reading data from the file. If `null` or `-1`, data will be read from the current file position, and the position will be updated. If `position` is a non-negative integer, the current file position will remain unchanged. \*\*Default:\*\* `null` \* Returns: {Promise} Fulfills upon success with an object with two properties: \* `bytesRead` {integer} The number of bytes read \* `buffer` {Buffer|TypedArray|DataView} A reference to the passed in `buffer` argument. Reads data from the file and stores that in the given buffer. If the file is not modified concurrently, the end-of-file is reached when the number of bytes read is zero. #### `filehandle.read([options])` \* `options` {Object} \* `buffer` {Buffer|TypedArray|DataView} A buffer that will be filled with the file data read. \*\*Default:\*\* `Buffer.alloc(16384)` \* `offset` {integer} The location in the buffer at which to start filling. \*\*Default:\*\* `0` \* `length` {integer} The number of bytes to read. \*\*Default:\*\* `buffer.byteLength - offset` \* `position` {integer|bigint|null} The location where to begin reading data from the file. If `null` or `-1`, data will be read from the current file position, and the position will be updated. If `position` is a non-negative integer, the current file position will remain unchanged. \*\*Default:\*\*: `null` \* Returns: {Promise} Fulfills upon success with an object with two properties: \* `bytesRead` {integer} The number of bytes read \* `buffer` {Buffer|TypedArray|DataView} A reference to the passed in `buffer` argument. Reads data from the file and stores that in the given buffer. If the file is not modified concurrently, the end-of-file is reached when the number of bytes read is zero. #### `filehandle.read(buffer[, options])` \* `buffer` {Buffer|TypedArray|DataView} A buffer that will be filled with the file data read. \* `options` {Object} \* `offset` {integer} The location in the buffer at which to start filling. \*\*Default:\*\* `0` \* `length` {integer} The number of bytes to read. \*\*Default:\*\* `buffer.byteLength - offset` \* `position` {integer|bigint|null} The location where to begin reading data from the file. If `null` or `-1`, data will be read from the current file position, and the position will be updated. If `position` is a non-negative integer, | https://github.com/nodejs/node/blob/main//doc/api/fs.md | main | nodejs | [
-0.025757109746336937,
0.04321364313364029,
-0.06814727187156677,
0.04336577281355858,
0.016103997826576233,
-0.014549074694514275,
0.002184309996664524,
0.0653756707906723,
0.03272107243537903,
0.060652077198028564,
-0.04478298872709274,
0.0468355193734169,
-0.04204094782471657,
0.0028904... | 0.085619 |
`length` {integer} The number of bytes to read. \*\*Default:\*\* `buffer.byteLength - offset` \* `position` {integer|bigint|null} The location where to begin reading data from the file. If `null` or `-1`, data will be read from the current file position, and the position will be updated. If `position` is a non-negative integer, the current file position will remain unchanged. \*\*Default:\*\*: `null` \* Returns: {Promise} Fulfills upon success with an object with two properties: \* `bytesRead` {integer} The number of bytes read \* `buffer` {Buffer|TypedArray|DataView} A reference to the passed in `buffer` argument. Reads data from the file and stores that in the given buffer. If the file is not modified concurrently, the end-of-file is reached when the number of bytes read is zero. #### `filehandle.readableWebStream([options])` \* `options` {Object} \* `autoClose` {boolean} When true, causes the {FileHandle} to be closed when the stream is closed. \*\*Default:\*\* `false` \* Returns: {ReadableStream} Returns a byte-oriented `ReadableStream` that may be used to read the file's contents. An error will be thrown if this method is called more than once or is called after the `FileHandle` is closed or closing. ```mjs import { open, } from 'node:fs/promises'; const file = await open('./some/file/to/read'); for await (const chunk of file.readableWebStream()) console.log(chunk); await file.close(); ``` ```cjs const { open, } = require('node:fs/promises'); (async () => { const file = await open('./some/file/to/read'); for await (const chunk of file.readableWebStream()) console.log(chunk); await file.close(); })(); ``` While the `ReadableStream` will read the file to completion, it will not close the `FileHandle` automatically. User code must still call the `fileHandle.close()` method unless the `autoClose` option is set to `true`. #### `filehandle.readFile(options)` \* `options` {Object|string} \* `encoding` {string|null} \*\*Default:\*\* `null` \* `signal` {AbortSignal} allows aborting an in-progress readFile \* Returns: {Promise} Fulfills upon a successful read with the contents of the file. If no encoding is specified (using `options.encoding`), the data is returned as a {Buffer} object. Otherwise, the data will be a string. Asynchronously reads the entire contents of a file. If `options` is a string, then it specifies the `encoding`. The {FileHandle} has to support reading. If one or more `filehandle.read()` calls are made on a file handle and then a `filehandle.readFile()` call is made, the data will be read from the current position till the end of the file. It doesn't always read from the beginning of the file. #### `filehandle.readLines([options])` \* `options` {Object} \* `encoding` {string} \*\*Default:\*\* `null` \* `autoClose` {boolean} \*\*Default:\*\* `true` \* `emitClose` {boolean} \*\*Default:\*\* `true` \* `start` {integer} \* `end` {integer} \*\*Default:\*\* `Infinity` \* `highWaterMark` {integer} \*\*Default:\*\* `64 \* 1024` \* Returns: {readline.InterfaceConstructor} Convenience method to create a `readline` interface and stream over the file. See [`filehandle.createReadStream()`][] for the options. ```mjs import { open } from 'node:fs/promises'; const file = await open('./some/file/to/read'); for await (const line of file.readLines()) { console.log(line); } ``` ```cjs const { open } = require('node:fs/promises'); (async () => { const file = await open('./some/file/to/read'); for await (const line of file.readLines()) { console.log(line); } })(); ``` #### `filehandle.readv(buffers[, position])` \* `buffers` {Buffer\[]|TypedArray\[]|DataView\[]} \* `position` {integer|null} The offset from the beginning of the file where the data should be read from. If `position` is not a `number`, the data will be read from the current position. \*\*Default:\*\* `null` \* Returns: {Promise} Fulfills upon success an object containing two properties: \* `bytesRead` {integer} the number of bytes read \* `buffers` {Buffer\[]|TypedArray\[]|DataView\[]} property containing a reference to the `buffers` input. Read from a file and write to an array of {ArrayBufferView}s #### `filehandle.stat([options])` \* `options` {Object} \* `bigint` {boolean} Whether the numeric values in the returned {fs.Stats} object should be `bigint`. \*\*Default:\*\* `false`. \* Returns: {Promise} Fulfills with an | https://github.com/nodejs/node/blob/main//doc/api/fs.md | main | nodejs | [
-0.04588748887181282,
0.02309797704219818,
-0.06186661124229431,
0.019334053620696068,
-0.0627562627196312,
-0.03988807648420334,
0.0575818233191967,
0.07220199704170227,
0.024523934349417686,
0.014890161342918873,
-0.012010050006210804,
0.07957080006599426,
-0.01578455977141857,
-0.051703... | 0.099131 |
\* `buffers` {Buffer\[]|TypedArray\[]|DataView\[]} property containing a reference to the `buffers` input. Read from a file and write to an array of {ArrayBufferView}s #### `filehandle.stat([options])` \* `options` {Object} \* `bigint` {boolean} Whether the numeric values in the returned {fs.Stats} object should be `bigint`. \*\*Default:\*\* `false`. \* Returns: {Promise} Fulfills with an {fs.Stats} for the file. #### `filehandle.sync()` \* Returns: {Promise} Fulfills with `undefined` upon success. Request that all data for the open file descriptor is flushed to the storage device. The specific implementation is operating system and device specific. Refer to the POSIX fsync(2) documentation for more detail. #### `filehandle.truncate(len)` \* `len` {integer} \*\*Default:\*\* `0` \* Returns: {Promise} Fulfills with `undefined` upon success. Truncates the file. If the file was larger than `len` bytes, only the first `len` bytes will be retained in the file. The following example retains only the first four bytes of the file: ```mjs import { open } from 'node:fs/promises'; let filehandle = null; try { filehandle = await open('temp.txt', 'r+'); await filehandle.truncate(4); } finally { await filehandle?.close(); } ``` If the file previously was shorter than `len` bytes, it is extended, and the extended part is filled with null bytes (`'\0'`): If `len` is negative then `0` will be used. #### `filehandle.utimes(atime, mtime)` \* `atime` {number|string|Date} \* `mtime` {number|string|Date} \* Returns: {Promise} Change the file system timestamps of the object referenced by the {FileHandle} then fulfills the promise with no arguments upon success. #### `filehandle.write(buffer, offset[, length[, position]])` \* `buffer` {Buffer|TypedArray|DataView} \* `offset` {integer} The start position from within `buffer` where the data to write begins. \* `length` {integer} The number of bytes from `buffer` to write. \*\*Default:\*\* `buffer.byteLength - offset` \* `position` {integer|null} The offset from the beginning of the file where the data from `buffer` should be written. If `position` is not a `number`, the data will be written at the current position. See the POSIX pwrite(2) documentation for more detail. \*\*Default:\*\* `null` \* Returns: {Promise} Write `buffer` to the file. The promise is fulfilled with an object containing two properties: \* `bytesWritten` {integer} the number of bytes written \* `buffer` {Buffer|TypedArray|DataView} a reference to the `buffer` written. It is unsafe to use `filehandle.write()` multiple times on the same file without waiting for the promise to be fulfilled (or rejected). For this scenario, use [`filehandle.createWriteStream()`][]. On Linux, positional writes do not work when the file is opened in append mode. The kernel ignores the position argument and always appends the data to the end of the file. #### `filehandle.write(buffer[, options])` \* `buffer` {Buffer|TypedArray|DataView} \* `options` {Object} \* `offset` {integer} \*\*Default:\*\* `0` \* `length` {integer} \*\*Default:\*\* `buffer.byteLength - offset` \* `position` {integer|null} \*\*Default:\*\* `null` \* Returns: {Promise} Write `buffer` to the file. Similar to the above `filehandle.write` function, this version takes an optional `options` object. If no `options` object is specified, it will default with the above values. #### `filehandle.write(string[, position[, encoding]])` \* `string` {string} \* `position` {integer|null} The offset from the beginning of the file where the data from `string` should be written. If `position` is not a `number` the data will be written at the current position. See the POSIX pwrite(2) documentation for more detail. \*\*Default:\*\* `null` \* `encoding` {string} The expected string encoding. \*\*Default:\*\* `'utf8'` \* Returns: {Promise} Write `string` to the file. If `string` is not a string, the promise is rejected with an error. The promise is fulfilled with an object containing two properties: \* `bytesWritten` {integer} the number of bytes written \* `buffer` {string} a reference to the `string` written. It is unsafe to use `filehandle.write()` multiple times on the same file without waiting for the promise to be | https://github.com/nodejs/node/blob/main//doc/api/fs.md | main | nodejs | [
-0.009000729769468307,
0.056242331862449646,
-0.06529513746500015,
0.04122548922896385,
-0.047993194311857224,
-0.08144321292638779,
0.0661262571811676,
0.0897597000002861,
0.04140762984752655,
-0.0062387725338339806,
-0.04280438646674156,
0.046864695847034454,
-0.07292044907808304,
-0.015... | 0.110317 |
rejected with an error. The promise is fulfilled with an object containing two properties: \* `bytesWritten` {integer} the number of bytes written \* `buffer` {string} a reference to the `string` written. It is unsafe to use `filehandle.write()` multiple times on the same file without waiting for the promise to be fulfilled (or rejected). For this scenario, use [`filehandle.createWriteStream()`][]. On Linux, positional writes do not work when the file is opened in append mode. The kernel ignores the position argument and always appends the data to the end of the file. #### `filehandle.writeFile(data, options)` \* `data` {string|Buffer|TypedArray|DataView|AsyncIterable|Iterable|Stream} \* `options` {Object|string} \* `encoding` {string|null} The expected character encoding when `data` is a string. \*\*Default:\*\* `'utf8'` \* `signal` {AbortSignal|undefined} allows aborting an in-progress writeFile. \*\*Default:\*\* `undefined` \* Returns: {Promise} Asynchronously writes data to a file, replacing the file if it already exists. `data` can be a string, a buffer, an {AsyncIterable}, or an {Iterable} object. The promise is fulfilled with no arguments upon success. If `options` is a string, then it specifies the `encoding`. The {FileHandle} has to support writing. It is unsafe to use `filehandle.writeFile()` multiple times on the same file without waiting for the promise to be fulfilled (or rejected). If one or more `filehandle.write()` calls are made on a file handle and then a `filehandle.writeFile()` call is made, the data will be written from the current position till the end of the file. It doesn't always write from the beginning of the file. #### `filehandle.writev(buffers[, position])` \* `buffers` {Buffer\[]|TypedArray\[]|DataView\[]} \* `position` {integer|null} The offset from the beginning of the file where the data from `buffers` should be written. If `position` is not a `number`, the data will be written at the current position. \*\*Default:\*\* `null` \* Returns: {Promise} Write an array of {ArrayBufferView}s to the file. The promise is fulfilled with an object containing a two properties: \* `bytesWritten` {integer} the number of bytes written \* `buffers` {Buffer\[]|TypedArray\[]|DataView\[]} a reference to the `buffers` input. It is unsafe to call `writev()` multiple times on the same file without waiting for the promise to be fulfilled (or rejected). On Linux, positional writes don't work when the file is opened in append mode. The kernel ignores the position argument and always appends the data to the end of the file. #### `filehandle[Symbol.asyncDispose]()` Calls `filehandle.close()` and returns a promise that fulfills when the filehandle is closed. ### `fsPromises.access(path[, mode])` \* `path` {string|Buffer|URL} \* `mode` {integer} \*\*Default:\*\* `fs.constants.F\_OK` \* Returns: {Promise} Fulfills with `undefined` upon success. Tests a user's permissions for the file or directory specified by `path`. The `mode` argument is an optional integer that specifies the accessibility checks to be performed. `mode` should be either the value `fs.constants.F\_OK` or a mask consisting of the bitwise OR of any of `fs.constants.R\_OK`, `fs.constants.W\_OK`, and `fs.constants.X\_OK` (e.g. `fs.constants.W\_OK | fs.constants.R\_OK`). Check [File access constants][] for possible values of `mode`. If the accessibility check is successful, the promise is fulfilled with no value. If any of the accessibility checks fail, the promise is rejected with an {Error} object. The following example checks if the file `/etc/passwd` can be read and written by the current process. ```mjs import { access, constants } from 'node:fs/promises'; try { await access('/etc/passwd', constants.R\_OK | constants.W\_OK); console.log('can access'); } catch { console.error('cannot access'); } ``` Using `fsPromises.access()` to check for the accessibility of a file before calling `fsPromises.open()` is not recommended. Doing so introduces a race condition, since other processes may change the file's state between the two calls. Instead, user code should open/read/write the file directly and handle the error raised if the file is not accessible. ### `fsPromises.appendFile(path, data[, options])` \* | https://github.com/nodejs/node/blob/main//doc/api/fs.md | main | nodejs | [
-0.032028887420892715,
-0.012521956115961075,
0.018077492713928223,
0.0710444226861,
-0.0641215443611145,
-0.05607061833143234,
0.013715280219912529,
0.08714139461517334,
0.06567172706127167,
0.026378115639090538,
-0.019679633900523186,
0.061917923390865326,
-0.008762641809880733,
-0.04101... | 0.004914 |
a file before calling `fsPromises.open()` is not recommended. Doing so introduces a race condition, since other processes may change the file's state between the two calls. Instead, user code should open/read/write the file directly and handle the error raised if the file is not accessible. ### `fsPromises.appendFile(path, data[, options])` \* `path` {string|Buffer|URL|FileHandle} filename or {FileHandle} \* `data` {string|Buffer} \* `options` {Object|string} \* `encoding` {string|null} \*\*Default:\*\* `'utf8'` \* `mode` {integer} \*\*Default:\*\* `0o666` \* `flag` {string} See [support of file system `flags`][]. \*\*Default:\*\* `'a'`. \* `flush` {boolean} If `true`, the underlying file descriptor is flushed prior to closing it. \*\*Default:\*\* `false`. \* Returns: {Promise} Fulfills with `undefined` upon success. Asynchronously append data to a file, creating the file if it does not yet exist. `data` can be a string or a {Buffer}. If `options` is a string, then it specifies the `encoding`. The `mode` option only affects the newly created file. See [`fs.open()`][] for more details. The `path` may be specified as a {FileHandle} that has been opened for appending (using `fsPromises.open()`). ### `fsPromises.chmod(path, mode)` \* `path` {string|Buffer|URL} \* `mode` {string|integer} \* Returns: {Promise} Fulfills with `undefined` upon success. Changes the permissions of a file. ### `fsPromises.chown(path, uid, gid)` \* `path` {string|Buffer|URL} \* `uid` {integer} \* `gid` {integer} \* Returns: {Promise} Fulfills with `undefined` upon success. Changes the ownership of a file. ### `fsPromises.copyFile(src, dest[, mode])` \* `src` {string|Buffer|URL} source filename to copy \* `dest` {string|Buffer|URL} destination filename of the copy operation \* `mode` {integer} Optional modifiers that specify the behavior of the copy operation. It is possible to create a mask consisting of the bitwise OR of two or more values (e.g. `fs.constants.COPYFILE\_EXCL | fs.constants.COPYFILE\_FICLONE`) \*\*Default:\*\* `0`. \* `fs.constants.COPYFILE\_EXCL`: The copy operation will fail if `dest` already exists. \* `fs.constants.COPYFILE\_FICLONE`: The copy operation will attempt to create a copy-on-write reflink. If the platform does not support copy-on-write, then a fallback copy mechanism is used. \* `fs.constants.COPYFILE\_FICLONE\_FORCE`: The copy operation will attempt to create a copy-on-write reflink. If the platform does not support copy-on-write, then the operation will fail. \* Returns: {Promise} Fulfills with `undefined` upon success. Asynchronously copies `src` to `dest`. By default, `dest` is overwritten if it already exists. No guarantees are made about the atomicity of the copy operation. If an error occurs after the destination file has been opened for writing, an attempt will be made to remove the destination. ```mjs import { copyFile, constants } from 'node:fs/promises'; try { await copyFile('source.txt', 'destination.txt'); console.log('source.txt was copied to destination.txt'); } catch { console.error('The file could not be copied'); } // By using COPYFILE\_EXCL, the operation will fail if destination.txt exists. try { await copyFile('source.txt', 'destination.txt', constants.COPYFILE\_EXCL); console.log('source.txt was copied to destination.txt'); } catch { console.error('The file could not be copied'); } ``` ### `fsPromises.cp(src, dest[, options])` \* `src` {string|URL} source path to copy. \* `dest` {string|URL} destination path to copy to. \* `options` {Object} \* `dereference` {boolean} dereference symlinks. \*\*Default:\*\* `false`. \* `errorOnExist` {boolean} when `force` is `false`, and the destination exists, throw an error. \*\*Default:\*\* `false`. \* `filter` {Function} Function to filter copied files/directories. Return `true` to copy the item, `false` to ignore it. When ignoring a directory, all of its contents will be skipped as well. Can also return a `Promise` that resolves to `true` or `false` \*\*Default:\*\* `undefined`. \* `src` {string} source path to copy. \* `dest` {string} destination path to copy to. \* Returns: {boolean|Promise} A value that is coercible to `boolean` or a `Promise` that fulfils with such value. \* `force` {boolean} overwrite existing file or directory. The copy operation will ignore errors if you set this to false and the destination exists. Use | https://github.com/nodejs/node/blob/main//doc/api/fs.md | main | nodejs | [
-0.00593023793771863,
0.01741291768848896,
-0.08262238651514053,
0.027673859149217606,
-0.01852419413626194,
-0.06728993356227875,
0.016023078933358192,
0.16372990608215332,
-0.02315376326441765,
0.02827056124806404,
0.0008022210677154362,
0.040978867560625076,
-0.054263513535261154,
-0.02... | 0.045211 |
`dest` {string} destination path to copy to. \* Returns: {boolean|Promise} A value that is coercible to `boolean` or a `Promise` that fulfils with such value. \* `force` {boolean} overwrite existing file or directory. The copy operation will ignore errors if you set this to false and the destination exists. Use the `errorOnExist` option to change this behavior. \*\*Default:\*\* `true`. \* `mode` {integer} modifiers for copy operation. \*\*Default:\*\* `0`. See `mode` flag of [`fsPromises.copyFile()`][]. \* `preserveTimestamps` {boolean} When `true` timestamps from `src` will be preserved. \*\*Default:\*\* `false`. \* `recursive` {boolean} copy directories recursively \*\*Default:\*\* `false` \* `verbatimSymlinks` {boolean} When `true`, path resolution for symlinks will be skipped. \*\*Default:\*\* `false` \* Returns: {Promise} Fulfills with `undefined` upon success. Asynchronously copies the entire directory structure from `src` to `dest`, including subdirectories and files. When copying a directory to another directory, globs are not supported and behavior is similar to `cp dir1/ dir2/`. ### `fsPromises.glob(pattern[, options])` \* `pattern` {string|string\[]} \* `options` {Object} \* `cwd` {string|URL} current working directory. \*\*Default:\*\* `process.cwd()` \* `exclude` {Function|string\[]} Function to filter out files/directories or a list of glob patterns to be excluded. If a function is provided, return `true` to exclude the item, `false` to include it. \*\*Default:\*\* `undefined`. If a string array is provided, each string should be a glob pattern that specifies paths to exclude. Note: Negation patterns (e.g., '!foo.js') are not supported. \* `withFileTypes` {boolean} `true` if the glob should return paths as Dirents, `false` otherwise. \*\*Default:\*\* `false`. \* Returns: {AsyncIterator} An AsyncIterator that yields the paths of files that match the pattern. ```mjs import { glob } from 'node:fs/promises'; for await (const entry of glob('\*\*/\*.js')) console.log(entry); ``` ```cjs const { glob } = require('node:fs/promises'); (async () => { for await (const entry of glob('\*\*/\*.js')) console.log(entry); })(); ``` ### `fsPromises.lchmod(path, mode)` > Stability: 0 - Deprecated \* `path` {string|Buffer|URL} \* `mode` {integer} \* Returns: {Promise} Fulfills with `undefined` upon success. Changes the permissions on a symbolic link. This method is only implemented on macOS. ### `fsPromises.lchown(path, uid, gid)` \* `path` {string|Buffer|URL} \* `uid` {integer} \* `gid` {integer} \* Returns: {Promise} Fulfills with `undefined` upon success. Changes the ownership on a symbolic link. ### `fsPromises.lutimes(path, atime, mtime)` \* `path` {string|Buffer|URL} \* `atime` {number|string|Date} \* `mtime` {number|string|Date} \* Returns: {Promise} Fulfills with `undefined` upon success. Changes the access and modification times of a file in the same way as [`fsPromises.utimes()`][], with the difference that if the path refers to a symbolic link, then the link is not dereferenced: instead, the timestamps of the symbolic link itself are changed. ### `fsPromises.link(existingPath, newPath)` \* `existingPath` {string|Buffer|URL} \* `newPath` {string|Buffer|URL} \* Returns: {Promise} Fulfills with `undefined` upon success. Creates a new link from the `existingPath` to the `newPath`. See the POSIX link(2) documentation for more detail. ### `fsPromises.lstat(path[, options])` \* `path` {string|Buffer|URL} \* `options` {Object} \* `bigint` {boolean} Whether the numeric values in the returned {fs.Stats} object should be `bigint`. \*\*Default:\*\* `false`. \* Returns: {Promise} Fulfills with the {fs.Stats} object for the given symbolic link `path`. Equivalent to [`fsPromises.stat()`][] unless `path` refers to a symbolic link, in which case the link itself is stat-ed, not the file that it refers to. Refer to the POSIX lstat(2) document for more detail. ### `fsPromises.mkdir(path[, options])` \* `path` {string|Buffer|URL} \* `options` {Object|integer} \* `recursive` {boolean} \*\*Default:\*\* `false` \* `mode` {string|integer} Not supported on Windows. See [File modes][] for more details. \*\*Default:\*\* `0o777`. \* Returns: {Promise} Upon success, fulfills with `undefined` if `recursive` is `false`, or the first directory path created if `recursive` is `true`. Asynchronously creates a directory. The optional `options` argument can be an integer specifying `mode` (permission and sticky bits), or an | https://github.com/nodejs/node/blob/main//doc/api/fs.md | main | nodejs | [
-0.07293364405632019,
-0.0306519977748394,
-0.003521036822348833,
0.051674846559762955,
0.05223778635263443,
-0.07115233689546585,
0.06113043799996376,
0.052123818546533585,
0.034627605229616165,
0.03664343059062958,
0.04993539676070213,
-0.02527177706360817,
0.008888574317097664,
0.020769... | 0.047953 |
See [File modes][] for more details. \*\*Default:\*\* `0o777`. \* Returns: {Promise} Upon success, fulfills with `undefined` if `recursive` is `false`, or the first directory path created if `recursive` is `true`. Asynchronously creates a directory. The optional `options` argument can be an integer specifying `mode` (permission and sticky bits), or an object with a `mode` property and a `recursive` property indicating whether parent directories should be created. Calling `fsPromises.mkdir()` when `path` is a directory that exists results in a rejection only when `recursive` is false. ```mjs import { mkdir } from 'node:fs/promises'; try { const projectFolder = new URL('./test/project/', import.meta.url); const createDir = await mkdir(projectFolder, { recursive: true }); console.log(`created ${createDir}`); } catch (err) { console.error(err.message); } ``` ```cjs const { mkdir } = require('node:fs/promises'); const { join } = require('node:path'); async function makeDirectory() { const projectFolder = join(\_\_dirname, 'test', 'project'); const dirCreation = await mkdir(projectFolder, { recursive: true }); console.log(dirCreation); return dirCreation; } makeDirectory().catch(console.error); ``` ### `fsPromises.mkdtemp(prefix[, options])` \* `prefix` {string|Buffer|URL} \* `options` {string|Object} \* `encoding` {string} \*\*Default:\*\* `'utf8'` \* Returns: {Promise} Fulfills with a string containing the file system path of the newly created temporary directory. Creates a unique temporary directory. A unique directory name is generated by appending six random characters to the end of the provided `prefix`. Due to platform inconsistencies, avoid trailing `X` characters in `prefix`. Some platforms, notably the BSDs, can return more than six random characters, and replace trailing `X` characters in `prefix` with random characters. The optional `options` argument can be a string specifying an encoding, or an object with an `encoding` property specifying the character encoding to use. ```mjs import { mkdtemp } from 'node:fs/promises'; import { join } from 'node:path'; import { tmpdir } from 'node:os'; try { await mkdtemp(join(tmpdir(), 'foo-')); } catch (err) { console.error(err); } ``` The `fsPromises.mkdtemp()` method will append the six randomly selected characters directly to the `prefix` string. For instance, given a directory `/tmp`, if the intention is to create a temporary directory \_within\_ `/tmp`, the `prefix` must end with a trailing platform-specific path separator (`require('node:path').sep`). ### `fsPromises.mkdtempDisposable(prefix[, options])` \* `prefix` {string|Buffer|URL} \* `options` {string|Object} \* `encoding` {string} \*\*Default:\*\* `'utf8'` \* Returns: {Promise} Fulfills with a Promise for an async-disposable Object: \* `path` {string} The path of the created directory. \* `remove` {AsyncFunction} A function which removes the created directory. \* `[Symbol.asyncDispose]` {AsyncFunction} The same as `remove`. The resulting Promise holds an async-disposable object whose `path` property holds the created directory path. When the object is disposed, the directory and its contents will be removed asynchronously if it still exists. If the directory cannot be deleted, disposal will throw an error. The object has an async `remove()` method which will perform the same task. Both this function and the disposal function on the resulting object are async, so it should be used with `await` + `await using` as in `await using dir = await fsPromises.mkdtempDisposable('prefix')`. For detailed information, see the documentation of [`fsPromises.mkdtemp()`][]. The optional `options` argument can be a string specifying an encoding, or an object with an `encoding` property specifying the character encoding to use. ### `fsPromises.open(path, flags[, mode])` \* `path` {string|Buffer|URL} \* `flags` {string|number} See [support of file system `flags`][]. \*\*Default:\*\* `'r'`. \* `mode` {string|integer} Sets the file mode (permission and sticky bits) if the file is created. See [File modes][] for more details. \*\*Default:\*\* `0o666` (readable and writable) \* Returns: {Promise} Fulfills with a {FileHandle} object. Opens a {FileHandle}. Refer to the POSIX open(2) documentation for more detail. Some characters (`< > : " / \ | ? \*`) are reserved under Windows as documented by [Naming Files, Paths, and Namespaces][]. Under | https://github.com/nodejs/node/blob/main//doc/api/fs.md | main | nodejs | [
-0.06615982204675674,
0.01381671242415905,
-0.004241532646119595,
0.08360745012760162,
0.057448167353868484,
-0.07763510197401047,
-0.002524890238419175,
0.10937343537807465,
0.06352361291646957,
0.0015172904822975397,
0.04211350157856941,
0.020234255120158195,
-0.026511918753385544,
0.081... | 0.072743 |
details. \*\*Default:\*\* `0o666` (readable and writable) \* Returns: {Promise} Fulfills with a {FileHandle} object. Opens a {FileHandle}. Refer to the POSIX open(2) documentation for more detail. Some characters (`< > : " / \ | ? \*`) are reserved under Windows as documented by [Naming Files, Paths, and Namespaces][]. Under NTFS, if the filename contains a colon, Node.js will open a file system stream, as described by [this MSDN page][MSDN-Using-Streams]. ### `fsPromises.opendir(path[, options])` \* `path` {string|Buffer|URL} \* `options` {Object} \* `encoding` {string|null} \*\*Default:\*\* `'utf8'` \* `bufferSize` {number} Number of directory entries that are buffered internally when reading from the directory. Higher values lead to better performance but higher memory usage. \*\*Default:\*\* `32` \* `recursive` {boolean} Resolved `Dir` will be an {AsyncIterable} containing all sub files and directories. \*\*Default:\*\* `false` \* Returns: {Promise} Fulfills with an {fs.Dir}. Asynchronously open a directory for iterative scanning. See the POSIX opendir(3) documentation for more detail. Creates an {fs.Dir}, which contains all further functions for reading from and cleaning up the directory. The `encoding` option sets the encoding for the `path` while opening the directory and subsequent read operations. Example using async iteration: ```mjs import { opendir } from 'node:fs/promises'; try { const dir = await opendir('./'); for await (const dirent of dir) console.log(dirent.name); } catch (err) { console.error(err); } ``` When using the async iterator, the {fs.Dir} object will be automatically closed after the iterator exits. ### `fsPromises.readdir(path[, options])` \* `path` {string|Buffer|URL} \* `options` {string|Object} \* `encoding` {string} \*\*Default:\*\* `'utf8'` \* `withFileTypes` {boolean} \*\*Default:\*\* `false` \* `recursive` {boolean} If `true`, reads the contents of a directory recursively. In recursive mode, it will list all files, sub files, and directories. \*\*Default:\*\* `false`. \* Returns: {Promise} Fulfills with an array of the names of the files in the directory excluding `'.'` and `'..'`. Reads the contents of a directory. The optional `options` argument can be a string specifying an encoding, or an object with an `encoding` property specifying the character encoding to use for the filenames. If the `encoding` is set to `'buffer'`, the filenames returned will be passed as {Buffer} objects. If `options.withFileTypes` is set to `true`, the returned array will contain {fs.Dirent} objects. ```mjs import { readdir } from 'node:fs/promises'; try { const files = await readdir(path); for (const file of files) console.log(file); } catch (err) { console.error(err); } ``` ### `fsPromises.readFile(path[, options])` \* `path` {string|Buffer|URL|FileHandle} filename or `FileHandle` \* `options` {Object|string} \* `encoding` {string|null} \*\*Default:\*\* `null` \* `flag` {string} See [support of file system `flags`][]. \*\*Default:\*\* `'r'`. \* `signal` {AbortSignal} allows aborting an in-progress readFile \* Returns: {Promise} Fulfills with the contents of the file. Asynchronously reads the entire contents of a file. If no encoding is specified (using `options.encoding`), the data is returned as a {Buffer} object. Otherwise, the data will be a string. If `options` is a string, then it specifies the encoding. When the `path` is a directory, the behavior of `fsPromises.readFile()` is platform-specific. On macOS, Linux, and Windows, the promise will be rejected with an error. On FreeBSD, a representation of the directory's contents will be returned. An example of reading a `package.json` file located in the same directory of the running code: ```mjs import { readFile } from 'node:fs/promises'; try { const filePath = new URL('./package.json', import.meta.url); const contents = await readFile(filePath, { encoding: 'utf8' }); console.log(contents); } catch (err) { console.error(err.message); } ``` ```cjs const { readFile } = require('node:fs/promises'); const { resolve } = require('node:path'); async function logFile() { try { const filePath = resolve('./package.json'); const contents = await readFile(filePath, { encoding: 'utf8' }); console.log(contents); } catch (err) { console.error(err.message); } } logFile(); ``` It is | https://github.com/nodejs/node/blob/main//doc/api/fs.md | main | nodejs | [
-0.030673731118440628,
-0.002921045757830143,
-0.03336241468787193,
0.0641319677233696,
0.04199367016553879,
-0.04775887355208397,
-0.012010556645691395,
0.13255655765533447,
0.09721529483795166,
0.02689622901380062,
-0.050355348736047745,
0.06624724715948105,
-0.09512806683778763,
0.01411... | 0.149762 |
catch (err) { console.error(err.message); } ``` ```cjs const { readFile } = require('node:fs/promises'); const { resolve } = require('node:path'); async function logFile() { try { const filePath = resolve('./package.json'); const contents = await readFile(filePath, { encoding: 'utf8' }); console.log(contents); } catch (err) { console.error(err.message); } } logFile(); ``` It is possible to abort an ongoing `readFile` using an {AbortSignal}. If a request is aborted the promise returned is rejected with an `AbortError`: ```mjs import { readFile } from 'node:fs/promises'; try { const controller = new AbortController(); const { signal } = controller; const promise = readFile(fileName, { signal }); // Abort the request before the promise settles. controller.abort(); await promise; } catch (err) { // When a request is aborted - err is an AbortError console.error(err); } ``` Aborting an ongoing request does not abort individual operating system requests but rather the internal buffering `fs.readFile` performs. Any specified {FileHandle} has to support reading. ### `fsPromises.readlink(path[, options])` \* `path` {string|Buffer|URL} \* `options` {string|Object} \* `encoding` {string} \*\*Default:\*\* `'utf8'` \* Returns: {Promise} Fulfills with the `linkString` upon success. Reads the contents of the symbolic link referred to by `path`. See the POSIX readlink(2) documentation for more detail. The promise is fulfilled with the `linkString` upon success. The optional `options` argument can be a string specifying an encoding, or an object with an `encoding` property specifying the character encoding to use for the link path returned. If the `encoding` is set to `'buffer'`, the link path returned will be passed as a {Buffer} object. ### `fsPromises.realpath(path[, options])` \* `path` {string|Buffer|URL} \* `options` {string|Object} \* `encoding` {string} \*\*Default:\*\* `'utf8'` \* Returns: {Promise} Fulfills with the resolved path upon success. Determines the actual location of `path` using the same semantics as the `fs.realpath.native()` function. Only paths that can be converted to UTF8 strings are supported. The optional `options` argument can be a string specifying an encoding, or an object with an `encoding` property specifying the character encoding to use for the path. If the `encoding` is set to `'buffer'`, the path returned will be passed as a {Buffer} object. On Linux, when Node.js is linked against musl libc, the procfs file system must be mounted on `/proc` in order for this function to work. Glibc does not have this restriction. ### `fsPromises.rename(oldPath, newPath)` \* `oldPath` {string|Buffer|URL} \* `newPath` {string|Buffer|URL} \* Returns: {Promise} Fulfills with `undefined` upon success. Renames `oldPath` to `newPath`. ### `fsPromises.rmdir(path[, options])` \* `path` {string|Buffer|URL} \* `options` {Object} There are currently no options exposed. There used to be options for `recursive`, `maxBusyTries`, and `emfileWait` but they were deprecated and removed. The `options` argument is still accepted for backwards compatibility but it is not used. \* Returns: {Promise} Fulfills with `undefined` upon success. Removes the directory identified by `path`. Using `fsPromises.rmdir()` on a file (not a directory) results in the promise being rejected with an `ENOENT` error on Windows and an `ENOTDIR` error on POSIX. To get a behavior similar to the `rm -rf` Unix command, use [`fsPromises.rm()`][] with options `{ recursive: true, force: true }`. ### `fsPromises.rm(path[, options])` \* `path` {string|Buffer|URL} \* `options` {Object} \* `force` {boolean} When `true`, exceptions will be ignored if `path` does not exist. \*\*Default:\*\* `false`. \* `maxRetries` {integer} If an `EBUSY`, `EMFILE`, `ENFILE`, `ENOTEMPTY`, or `EPERM` error is encountered, Node.js will retry the operation with a linear backoff wait of `retryDelay` milliseconds longer on each try. This option represents the number of retries. This option is ignored if the `recursive` option is not `true`. \*\*Default:\*\* `0`. \* `recursive` {boolean} If `true`, perform a recursive directory removal. In recursive mode operations are retried on failure. \*\*Default:\*\* `false`. \* `retryDelay` | https://github.com/nodejs/node/blob/main//doc/api/fs.md | main | nodejs | [
-0.09077340364456177,
0.04989590123295784,
0.03485608845949173,
0.030387867242097855,
0.04413618519902229,
-0.034829795360565186,
-0.017452917993068695,
0.10628944635391235,
0.07964780926704407,
0.023598436266183853,
-0.021983318030834198,
0.05248687043786049,
-0.009581396356225014,
0.0002... | 0.096032 |
wait of `retryDelay` milliseconds longer on each try. This option represents the number of retries. This option is ignored if the `recursive` option is not `true`. \*\*Default:\*\* `0`. \* `recursive` {boolean} If `true`, perform a recursive directory removal. In recursive mode operations are retried on failure. \*\*Default:\*\* `false`. \* `retryDelay` {integer} The amount of time in milliseconds to wait between retries. This option is ignored if the `recursive` option is not `true`. \*\*Default:\*\* `100`. \* Returns: {Promise} Fulfills with `undefined` upon success. Removes files and directories (modeled on the standard POSIX `rm` utility). ### `fsPromises.stat(path[, options])` \* `path` {string|Buffer|URL} \* `options` {Object} \* `bigint` {boolean} Whether the numeric values in the returned {fs.Stats} object should be `bigint`. \*\*Default:\*\* `false`. \* Returns: {Promise} Fulfills with the {fs.Stats} object for the given `path`. ### `fsPromises.statfs(path[, options])` \* `path` {string|Buffer|URL} \* `options` {Object} \* `bigint` {boolean} Whether the numeric values in the returned {fs.StatFs} object should be `bigint`. \*\*Default:\*\* `false`. \* Returns: {Promise} Fulfills with the {fs.StatFs} object for the given `path`. ### `fsPromises.symlink(target, path[, type])` \* `target` {string|Buffer|URL} \* `path` {string|Buffer|URL} \* `type` {string|null} \*\*Default:\*\* `null` \* Returns: {Promise} Fulfills with `undefined` upon success. Creates a symbolic link. The `type` argument is only used on Windows platforms and can be one of `'dir'`, `'file'`, or `'junction'`. If the `type` argument is `null`, Node.js will autodetect `target` type and use `'file'` or `'dir'`. If the `target` does not exist, `'file'` will be used. Windows junction points require the destination path to be absolute. When using `'junction'`, the `target` argument will automatically be normalized to absolute path. Junction points on NTFS volumes can only point to directories. ### `fsPromises.truncate(path[, len])` \* `path` {string|Buffer|URL} \* `len` {integer} \*\*Default:\*\* `0` \* Returns: {Promise} Fulfills with `undefined` upon success. Truncates (shortens or extends the length) of the content at `path` to `len` bytes. ### `fsPromises.unlink(path)` \* `path` {string|Buffer|URL} \* Returns: {Promise} Fulfills with `undefined` upon success. If `path` refers to a symbolic link, then the link is removed without affecting the file or directory to which that link refers. If the `path` refers to a file path that is not a symbolic link, the file is deleted. See the POSIX unlink(2) documentation for more detail. ### `fsPromises.utimes(path, atime, mtime)` \* `path` {string|Buffer|URL} \* `atime` {number|string|Date} \* `mtime` {number|string|Date} \* Returns: {Promise} Fulfills with `undefined` upon success. Change the file system timestamps of the object referenced by `path`. The `atime` and `mtime` arguments follow these rules: \* Values can be either numbers representing Unix epoch time, `Date`s, or a numeric string like `'123456789.0'`. \* If the value can not be converted to a number, or is `NaN`, `Infinity`, or `-Infinity`, an `Error` will be thrown. ### `fsPromises.watch(filename[, options])` \* `filename` {string|Buffer|URL} \* `options` {string|Object} \* `persistent` {boolean} Indicates whether the process should continue to run as long as files are being watched. \*\*Default:\*\* `true`. \* `recursive` {boolean} Indicates whether all subdirectories should be watched, or only the current directory. This applies when a directory is specified, and only on supported platforms (See [caveats][]). \*\*Default:\*\* `false`. \* `encoding` {string} Specifies the character encoding to be used for the filename passed to the listener. \*\*Default:\*\* `'utf8'`. \* `signal` {AbortSignal} An {AbortSignal} used to signal when the watcher should stop. \* `maxQueue` {number} Specifies the number of events to queue between iterations of the {AsyncIterator} returned. \*\*Default:\*\* `2048`. \* `overflow` {string} Either `'ignore'` or `'throw'` when there are more events to be queued than `maxQueue` allows. `'ignore'` means overflow events are dropped and a warning is emitted, while `'throw'` means to throw an exception. \*\*Default:\*\* `'ignore'`. \* `ignore` {string|RegExp|Function|Array} Pattern(s) to | https://github.com/nodejs/node/blob/main//doc/api/fs.md | main | nodejs | [
-0.07452392578125,
0.0417320691049099,
-0.008784161880612373,
0.03838822618126869,
0.0030982960015535355,
-0.09900802373886108,
0.03082062304019928,
0.05685251206159592,
0.04922089725732803,
0.008621410466730595,
0.04189391806721687,
0.007237370125949383,
-0.03121228516101837,
0.0379219800... | 0.063081 |
iterations of the {AsyncIterator} returned. \*\*Default:\*\* `2048`. \* `overflow` {string} Either `'ignore'` or `'throw'` when there are more events to be queued than `maxQueue` allows. `'ignore'` means overflow events are dropped and a warning is emitted, while `'throw'` means to throw an exception. \*\*Default:\*\* `'ignore'`. \* `ignore` {string|RegExp|Function|Array} Pattern(s) to ignore. Strings are glob patterns (using [`minimatch`][]), RegExp patterns are tested against the filename, and functions receive the filename and return `true` to ignore. \*\*Default:\*\* `undefined`. \* Returns: {AsyncIterator} of objects with the properties: \* `eventType` {string} The type of change \* `filename` {string|Buffer|null} The name of the file changed. Returns an async iterator that watches for changes on `filename`, where `filename` is either a file or a directory. ```js const { watch } = require('node:fs/promises'); const ac = new AbortController(); const { signal } = ac; setTimeout(() => ac.abort(), 10000); (async () => { try { const watcher = watch(\_\_filename, { signal }); for await (const event of watcher) console.log(event); } catch (err) { if (err.name === 'AbortError') return; throw err; } })(); ``` On most platforms, `'rename'` is emitted whenever a filename appears or disappears in the directory. All the [caveats][] for `fs.watch()` also apply to `fsPromises.watch()`. ### `fsPromises.writeFile(file, data[, options])` \* `file` {string|Buffer|URL|FileHandle} filename or `FileHandle` \* `data` {string|Buffer|TypedArray|DataView|AsyncIterable|Iterable|Stream} \* `options` {Object|string} \* `encoding` {string|null} \*\*Default:\*\* `'utf8'` \* `mode` {integer} \*\*Default:\*\* `0o666` \* `flag` {string} See [support of file system `flags`][]. \*\*Default:\*\* `'w'`. \* `flush` {boolean} If all data is successfully written to the file, and `flush` is `true`, `filehandle.sync()` is used to flush the data. \*\*Default:\*\* `false`. \* `signal` {AbortSignal} allows aborting an in-progress writeFile \* Returns: {Promise} Fulfills with `undefined` upon success. Asynchronously writes data to a file, replacing the file if it already exists. `data` can be a string, a buffer, an {AsyncIterable}, or an {Iterable} object. The `encoding` option is ignored if `data` is a buffer. If `options` is a string, then it specifies the encoding. The `mode` option only affects the newly created file. See [`fs.open()`][] for more details. Any specified {FileHandle} has to support writing. It is unsafe to use `fsPromises.writeFile()` multiple times on the same file without waiting for the promise to be settled. Similarly to `fsPromises.readFile` - `fsPromises.writeFile` is a convenience method that performs multiple `write` calls internally to write the buffer passed to it. For performance sensitive code consider using [`fs.createWriteStream()`][] or [`filehandle.createWriteStream()`][]. It is possible to use an {AbortSignal} to cancel an `fsPromises.writeFile()`. Cancelation is "best effort", and some amount of data is likely still to be written. ```mjs import { writeFile } from 'node:fs/promises'; import { Buffer } from 'node:buffer'; try { const controller = new AbortController(); const { signal } = controller; const data = new Uint8Array(Buffer.from('Hello Node.js')); const promise = writeFile('message.txt', data, { signal }); // Abort the request before the promise settles. controller.abort(); await promise; } catch (err) { // When a request is aborted - err is an AbortError console.error(err); } ``` Aborting an ongoing request does not abort individual operating system requests but rather the internal buffering `fs.writeFile` performs. ### `fsPromises.constants` \* Type: {Object} Returns an object containing commonly used constants for file system operations. The object is the same as `fs.constants`. See [FS constants][] for more details. ## Callback API The callback APIs perform all operations asynchronously, without blocking the event loop, then invoke a callback function upon completion or error. The callback APIs use the underlying Node.js threadpool to perform file system operations off the event loop thread. These operations are not synchronized or threadsafe. Care must be taken when performing multiple concurrent modifications on the same file or | https://github.com/nodejs/node/blob/main//doc/api/fs.md | main | nodejs | [
-0.10596445202827454,
0.08671995252370834,
-0.03318031504750252,
0.07835793495178223,
-0.03186347335577011,
-0.059372298419475555,
0.04078087955713272,
0.01857161335647106,
0.03222593292593956,
-0.028110187500715256,
-0.022062668576836586,
0.06145457923412323,
-0.004732123576104641,
-0.068... | 0.114159 |
event loop, then invoke a callback function upon completion or error. The callback APIs use the underlying Node.js threadpool to perform file system operations off the event loop thread. These operations are not synchronized or threadsafe. Care must be taken when performing multiple concurrent modifications on the same file or data corruption may occur. ### `fs.access(path[, mode], callback)` \* `path` {string|Buffer|URL} \* `mode` {integer} \*\*Default:\*\* `fs.constants.F\_OK` \* `callback` {Function} \* `err` {Error} Tests a user's permissions for the file or directory specified by `path`. The `mode` argument is an optional integer that specifies the accessibility checks to be performed. `mode` should be either the value `fs.constants.F\_OK` or a mask consisting of the bitwise OR of any of `fs.constants.R\_OK`, `fs.constants.W\_OK`, and `fs.constants.X\_OK` (e.g. `fs.constants.W\_OK | fs.constants.R\_OK`). Check [File access constants][] for possible values of `mode`. The final argument, `callback`, is a callback function that is invoked with a possible error argument. If any of the accessibility checks fail, the error argument will be an `Error` object. The following examples check if `package.json` exists, and if it is readable or writable. ```mjs import { access, constants } from 'node:fs'; const file = 'package.json'; // Check if the file exists in the current directory. access(file, constants.F\_OK, (err) => { console.log(`${file} ${err ? 'does not exist' : 'exists'}`); }); // Check if the file is readable. access(file, constants.R\_OK, (err) => { console.log(`${file} ${err ? 'is not readable' : 'is readable'}`); }); // Check if the file is writable. access(file, constants.W\_OK, (err) => { console.log(`${file} ${err ? 'is not writable' : 'is writable'}`); }); // Check if the file is readable and writable. access(file, constants.R\_OK | constants.W\_OK, (err) => { console.log(`${file} ${err ? 'is not' : 'is'} readable and writable`); }); ``` Do not use `fs.access()` to check for the accessibility of a file before calling `fs.open()`, `fs.readFile()`, or `fs.writeFile()`. Doing so introduces a race condition, since other processes may change the file's state between the two calls. Instead, user code should open/read/write the file directly and handle the error raised if the file is not accessible. \*\*write (NOT RECOMMENDED)\*\* ```mjs import { access, open, close } from 'node:fs'; access('myfile', (err) => { if (!err) { console.error('myfile already exists'); return; } open('myfile', 'wx', (err, fd) => { if (err) throw err; try { writeMyData(fd); } finally { close(fd, (err) => { if (err) throw err; }); } }); }); ``` \*\*write (RECOMMENDED)\*\* ```mjs import { open, close } from 'node:fs'; open('myfile', 'wx', (err, fd) => { if (err) { if (err.code === 'EEXIST') { console.error('myfile already exists'); return; } throw err; } try { writeMyData(fd); } finally { close(fd, (err) => { if (err) throw err; }); } }); ``` \*\*read (NOT RECOMMENDED)\*\* ```mjs import { access, open, close } from 'node:fs'; access('myfile', (err) => { if (err) { if (err.code === 'ENOENT') { console.error('myfile does not exist'); return; } throw err; } open('myfile', 'r', (err, fd) => { if (err) throw err; try { readMyData(fd); } finally { close(fd, (err) => { if (err) throw err; }); } }); }); ``` \*\*read (RECOMMENDED)\*\* ```mjs import { open, close } from 'node:fs'; open('myfile', 'r', (err, fd) => { if (err) { if (err.code === 'ENOENT') { console.error('myfile does not exist'); return; } throw err; } try { readMyData(fd); } finally { close(fd, (err) => { if (err) throw err; }); } }); ``` The "not recommended" examples above check for accessibility and then use the file; the "recommended" examples are better because they use the file directly and handle the error, if any. In general, check for the accessibility of a file only if the | https://github.com/nodejs/node/blob/main//doc/api/fs.md | main | nodejs | [
-0.056698236614465714,
0.014186779037117958,
-0.054487444460392,
0.056103941053152084,
0.050947993993759155,
-0.10753613710403442,
0.032613810151815414,
0.062163688242435455,
0.0708019956946373,
-0.027587907388806343,
-0.024897277355194092,
0.1053265705704689,
-0.03306387737393379,
-0.0221... | 0.114058 |
if (err) throw err; }); } }); ``` The "not recommended" examples above check for accessibility and then use the file; the "recommended" examples are better because they use the file directly and handle the error, if any. In general, check for the accessibility of a file only if the file will not be used directly, for example when its accessibility is a signal from another process. On Windows, access-control policies (ACLs) on a directory may limit access to a file or directory. The `fs.access()` function, however, does not check the ACL and therefore may report that a path is accessible even if the ACL restricts the user from reading or writing to it. ### `fs.appendFile(path, data[, options], callback)` \* `path` {string|Buffer|URL|number} filename or file descriptor \* `data` {string|Buffer} \* `options` {Object|string} \* `encoding` {string|null} \*\*Default:\*\* `'utf8'` \* `mode` {integer} \*\*Default:\*\* `0o666` \* `flag` {string} See [support of file system `flags`][]. \*\*Default:\*\* `'a'`. \* `flush` {boolean} If `true`, the underlying file descriptor is flushed prior to closing it. \*\*Default:\*\* `false`. \* `callback` {Function} \* `err` {Error} Asynchronously append data to a file, creating the file if it does not yet exist. `data` can be a string or a {Buffer}. The `mode` option only affects the newly created file. See [`fs.open()`][] for more details. ```mjs import { appendFile } from 'node:fs'; appendFile('message.txt', 'data to append', (err) => { if (err) throw err; console.log('The "data to append" was appended to file!'); }); ``` If `options` is a string, then it specifies the encoding: ```mjs import { appendFile } from 'node:fs'; appendFile('message.txt', 'data to append', 'utf8', callback); ``` The `path` may be specified as a numeric file descriptor that has been opened for appending (using `fs.open()` or `fs.openSync()`). The file descriptor will not be closed automatically. ```mjs import { open, close, appendFile } from 'node:fs'; function closeFd(fd) { close(fd, (err) => { if (err) throw err; }); } open('message.txt', 'a', (err, fd) => { if (err) throw err; try { appendFile(fd, 'data to append', 'utf8', (err) => { closeFd(fd); if (err) throw err; }); } catch (err) { closeFd(fd); throw err; } }); ``` ### `fs.chmod(path, mode, callback)` \* `path` {string|Buffer|URL} \* `mode` {string|integer} \* `callback` {Function} \* `err` {Error} Asynchronously changes the permissions of a file. No arguments other than a possible exception are given to the completion callback. See the POSIX chmod(2) documentation for more detail. ```mjs import { chmod } from 'node:fs'; chmod('my\_file.txt', 0o775, (err) => { if (err) throw err; console.log('The permissions for file "my\_file.txt" have been changed!'); }); ``` #### File modes The `mode` argument used in both the `fs.chmod()` and `fs.chmodSync()` methods is a numeric bitmask created using a logical OR of the following constants: | Constant | Octal | Description | | ---------------------- | ------- | ------------------------ | | `fs.constants.S\_IRUSR` | `0o400` | read by owner | | `fs.constants.S\_IWUSR` | `0o200` | write by owner | | `fs.constants.S\_IXUSR` | `0o100` | execute/search by owner | | `fs.constants.S\_IRGRP` | `0o40` | read by group | | `fs.constants.S\_IWGRP` | `0o20` | write by group | | `fs.constants.S\_IXGRP` | `0o10` | execute/search by group | | `fs.constants.S\_IROTH` | `0o4` | read by others | | `fs.constants.S\_IWOTH` | `0o2` | write by others | | `fs.constants.S\_IXOTH` | `0o1` | execute/search by others | An easier method of constructing the `mode` is to use a sequence of three octal digits (e.g. `765`). The left-most digit (`7` in the example), specifies the permissions for the file owner. The middle digit (`6` in the example), specifies permissions for the group. The right-most digit (`5` in the example), specifies the permissions for others. | | https://github.com/nodejs/node/blob/main//doc/api/fs.md | main | nodejs | [
-0.06815412640571594,
0.006569125689566135,
-0.11879821866750717,
0.05795028805732727,
0.024817850440740585,
-0.06185300275683403,
0.06370411813259125,
0.11040503531694412,
-0.005984250921756029,
0.0005116386455483735,
0.02462606318295002,
0.059675756841897964,
-0.0006961706676520407,
-0.0... | 0.043531 |
is to use a sequence of three octal digits (e.g. `765`). The left-most digit (`7` in the example), specifies the permissions for the file owner. The middle digit (`6` in the example), specifies permissions for the group. The right-most digit (`5` in the example), specifies the permissions for others. | Number | Description | | ------ | ------------------------ | | `7` | read, write, and execute | | `6` | read and write | | `5` | read and execute | | `4` | read only | | `3` | write and execute | | `2` | write only | | `1` | execute only | | `0` | no permission | For example, the octal value `0o765` means: \* The owner may read, write, and execute the file. \* The group may read and write the file. \* Others may read and execute the file. When using raw numbers where file modes are expected, any value larger than `0o777` may result in platform-specific behaviors that are not supported to work consistently. Therefore constants like `S\_ISVTX`, `S\_ISGID`, or `S\_ISUID` are not exposed in `fs.constants`. Caveats: on Windows only the write permission can be changed, and the distinction among the permissions of group, owner, or others is not implemented. ### `fs.chown(path, uid, gid, callback)` \* `path` {string|Buffer|URL} \* `uid` {integer} \* `gid` {integer} \* `callback` {Function} \* `err` {Error} Asynchronously changes owner and group of a file. No arguments other than a possible exception are given to the completion callback. See the POSIX chown(2) documentation for more detail. ### `fs.close(fd[, callback])` \* `fd` {integer} \* `callback` {Function} \* `err` {Error} Closes the file descriptor. No arguments other than a possible exception are given to the completion callback. Calling `fs.close()` on any file descriptor (`fd`) that is currently in use through any other `fs` operation may lead to undefined behavior. See the POSIX close(2) documentation for more detail. ### `fs.copyFile(src, dest[, mode], callback)` \* `src` {string|Buffer|URL} source filename to copy \* `dest` {string|Buffer|URL} destination filename of the copy operation \* `mode` {integer} modifiers for copy operation. \*\*Default:\*\* `0`. \* `callback` {Function} \* `err` {Error} Asynchronously copies `src` to `dest`. By default, `dest` is overwritten if it already exists. No arguments other than a possible exception are given to the callback function. Node.js makes no guarantees about the atomicity of the copy operation. If an error occurs after the destination file has been opened for writing, Node.js will attempt to remove the destination. `mode` is an optional integer that specifies the behavior of the copy operation. It is possible to create a mask consisting of the bitwise OR of two or more values (e.g. `fs.constants.COPYFILE\_EXCL | fs.constants.COPYFILE\_FICLONE`). \* `fs.constants.COPYFILE\_EXCL`: The copy operation will fail if `dest` already exists. \* `fs.constants.COPYFILE\_FICLONE`: The copy operation will attempt to create a copy-on-write reflink. If the platform does not support copy-on-write, then a fallback copy mechanism is used. \* `fs.constants.COPYFILE\_FICLONE\_FORCE`: The copy operation will attempt to create a copy-on-write reflink. If the platform does not support copy-on-write, then the operation will fail. ```mjs import { copyFile, constants } from 'node:fs'; function callback(err) { if (err) throw err; console.log('source.txt was copied to destination.txt'); } // destination.txt will be created or overwritten by default. copyFile('source.txt', 'destination.txt', callback); // By using COPYFILE\_EXCL, the operation will fail if destination.txt exists. copyFile('source.txt', 'destination.txt', constants.COPYFILE\_EXCL, callback); ``` ### `fs.cp(src, dest[, options], callback)` \* `src` {string|URL} source path to copy. \* `dest` {string|URL} destination path to copy to. \* `options` {Object} \* `dereference` {boolean} dereference symlinks. \*\*Default:\*\* `false`. \* `errorOnExist` {boolean} when `force` is `false`, and the destination exists, throw an error. \*\*Default:\*\* `false`. | https://github.com/nodejs/node/blob/main//doc/api/fs.md | main | nodejs | [
-0.009461532346904278,
-0.009493323042988777,
-0.11063522100448608,
-0.03645731881260872,
-0.030560359358787537,
-0.019053775817155838,
0.011060829274356365,
0.05860988423228264,
-0.04130179435014725,
0.007142720744013786,
0.03728051856160164,
0.017413314431905746,
0.008875424973666668,
-0... | 0.127805 |
'destination.txt', constants.COPYFILE\_EXCL, callback); ``` ### `fs.cp(src, dest[, options], callback)` \* `src` {string|URL} source path to copy. \* `dest` {string|URL} destination path to copy to. \* `options` {Object} \* `dereference` {boolean} dereference symlinks. \*\*Default:\*\* `false`. \* `errorOnExist` {boolean} when `force` is `false`, and the destination exists, throw an error. \*\*Default:\*\* `false`. \* `filter` {Function} Function to filter copied files/directories. Return `true` to copy the item, `false` to ignore it. When ignoring a directory, all of its contents will be skipped as well. Can also return a `Promise` that resolves to `true` or `false` \*\*Default:\*\* `undefined`. \* `src` {string} source path to copy. \* `dest` {string} destination path to copy to. \* Returns: {boolean|Promise} A value that is coercible to `boolean` or a `Promise` that fulfils with such value. \* `force` {boolean} overwrite existing file or directory. The copy operation will ignore errors if you set this to false and the destination exists. Use the `errorOnExist` option to change this behavior. \*\*Default:\*\* `true`. \* `mode` {integer} modifiers for copy operation. \*\*Default:\*\* `0`. See `mode` flag of [`fs.copyFile()`][]. \* `preserveTimestamps` {boolean} When `true` timestamps from `src` will be preserved. \*\*Default:\*\* `false`. \* `recursive` {boolean} copy directories recursively \*\*Default:\*\* `false` \* `verbatimSymlinks` {boolean} When `true`, path resolution for symlinks will be skipped. \*\*Default:\*\* `false` \* `callback` {Function} \* `err` {Error} Asynchronously copies the entire directory structure from `src` to `dest`, including subdirectories and files. When copying a directory to another directory, globs are not supported and behavior is similar to `cp dir1/ dir2/`. ### `fs.createReadStream(path[, options])` \* `path` {string|Buffer|URL} \* `options` {string|Object} \* `flags` {string} See [support of file system `flags`][]. \*\*Default:\*\* `'r'`. \* `encoding` {string} \*\*Default:\*\* `null` \* `fd` {integer|FileHandle} \*\*Default:\*\* `null` \* `mode` {integer} \*\*Default:\*\* `0o666` \* `autoClose` {boolean} \*\*Default:\*\* `true` \* `emitClose` {boolean} \*\*Default:\*\* `true` \* `start` {integer} \* `end` {integer} \*\*Default:\*\* `Infinity` \* `highWaterMark` {integer} \*\*Default:\*\* `64 \* 1024` \* `fs` {Object|null} \*\*Default:\*\* `null` \* `signal` {AbortSignal|null} \*\*Default:\*\* `null` \* Returns: {fs.ReadStream} `options` can include `start` and `end` values to read a range of bytes from the file instead of the entire file. Both `start` and `end` are inclusive and start counting at 0, allowed values are in the \[0, [`Number.MAX\_SAFE\_INTEGER`][]] range. If `fd` is specified and `start` is omitted or `undefined`, `fs.createReadStream()` reads sequentially from the current file position. The `encoding` can be any one of those accepted by {Buffer}. If `fd` is specified, `ReadStream` will ignore the `path` argument and will use the specified file descriptor. This means that no `'open'` event will be emitted. `fd` should be blocking; non-blocking `fd`s should be passed to {net.Socket}. If `fd` points to a character device that only supports blocking reads (such as keyboard or sound card), read operations do not finish until data is available. This can prevent the process from exiting and the stream from closing naturally. By default, the stream will emit a `'close'` event after it has been destroyed. Set the `emitClose` option to `false` to change this behavior. By providing the `fs` option, it is possible to override the corresponding `fs` implementations for `open`, `read`, and `close`. When providing the `fs` option, an override for `read` is required. If no `fd` is provided, an override for `open` is also required. If `autoClose` is `true`, an override for `close` is also required. ```mjs import { createReadStream } from 'node:fs'; // Create a stream from some character device. const stream = createReadStream('/dev/input/event0'); setTimeout(() => { stream.close(); // This may not close the stream. // Artificially marking end-of-stream, as if the underlying resource had // indicated end-of-file by itself, allows the stream to close. // This does not cancel | https://github.com/nodejs/node/blob/main//doc/api/fs.md | main | nodejs | [
-0.1328686624765396,
-0.004003711044788361,
0.02158961072564125,
0.08936778455972672,
0.05105117708444595,
-0.07823200523853302,
0.04256921261548996,
0.022501589730381966,
0.058423224836587906,
-0.027646804228425026,
0.03604191914200783,
-0.00196496257558465,
-0.02127741649746895,
0.028493... | 0.055991 |
from 'node:fs'; // Create a stream from some character device. const stream = createReadStream('/dev/input/event0'); setTimeout(() => { stream.close(); // This may not close the stream. // Artificially marking end-of-stream, as if the underlying resource had // indicated end-of-file by itself, allows the stream to close. // This does not cancel pending read operations, and if there is such an // operation, the process may still not be able to exit successfully // until it finishes. stream.push(null); stream.read(0); }, 100); ``` If `autoClose` is false, then the file descriptor won't be closed, even if there's an error. It is the application's responsibility to close it and make sure there's no file descriptor leak. If `autoClose` is set to true (default behavior), on `'error'` or `'end'` the file descriptor will be closed automatically. `mode` sets the file mode (permission and sticky bits), but only if the file was created. An example to read the last 10 bytes of a file which is 100 bytes long: ```mjs import { createReadStream } from 'node:fs'; createReadStream('sample.txt', { start: 90, end: 99 }); ``` If `options` is a string, then it specifies the encoding. ### `fs.createWriteStream(path[, options])` \* `path` {string|Buffer|URL} \* `options` {string|Object} \* `flags` {string} See [support of file system `flags`][]. \*\*Default:\*\* `'w'`. \* `encoding` {string} \*\*Default:\*\* `'utf8'` \* `fd` {integer|FileHandle} \*\*Default:\*\* `null` \* `mode` {integer} \*\*Default:\*\* `0o666` \* `autoClose` {boolean} \*\*Default:\*\* `true` \* `emitClose` {boolean} \*\*Default:\*\* `true` \* `start` {integer} \* `fs` {Object|null} \*\*Default:\*\* `null` \* `signal` {AbortSignal|null} \*\*Default:\*\* `null` \* `highWaterMark` {number} \*\*Default:\*\* `16384` \* `flush` {boolean} If `true`, the underlying file descriptor is flushed prior to closing it. \*\*Default:\*\* `false`. \* Returns: {fs.WriteStream} `options` may also include a `start` option to allow writing data at some position past the beginning of the file, allowed values are in the \[0, [`Number.MAX\_SAFE\_INTEGER`][]] range. Modifying a file rather than replacing it may require the `flags` option to be set to `r+` rather than the default `w`. The `encoding` can be any one of those accepted by {Buffer}. If `autoClose` is set to true (default behavior) on `'error'` or `'finish'` the file descriptor will be closed automatically. If `autoClose` is false, then the file descriptor won't be closed, even if there's an error. It is the application's responsibility to close it and make sure there's no file descriptor leak. By default, the stream will emit a `'close'` event after it has been destroyed. Set the `emitClose` option to `false` to change this behavior. By providing the `fs` option it is possible to override the corresponding `fs` implementations for `open`, `write`, `writev`, and `close`. Overriding `write()` without `writev()` can reduce performance as some optimizations (`\_writev()`) will be disabled. When providing the `fs` option, overrides for at least one of `write` and `writev` are required. If no `fd` option is supplied, an override for `open` is also required. If `autoClose` is `true`, an override for `close` is also required. Like {fs.ReadStream}, if `fd` is specified, {fs.WriteStream} will ignore the `path` argument and will use the specified file descriptor. This means that no `'open'` event will be emitted. `fd` should be blocking; non-blocking `fd`s should be passed to {net.Socket}. If `options` is a string, then it specifies the encoding. ### `fs.exists(path, callback)` > Stability: 0 - Deprecated: Use [`fs.stat()`][] or [`fs.access()`][] instead. \* `path` {string|Buffer|URL} \* `callback` {Function} \* `exists` {boolean} Test whether or not the element at the given `path` exists by checking with the file system. Then call the `callback` argument with either true or false: ```mjs import { exists } from 'node:fs'; exists('/etc/passwd', (e) => { console.log(e ? 'it exists' : 'no passwd!'); }); ``` \*\*The | https://github.com/nodejs/node/blob/main//doc/api/fs.md | main | nodejs | [
-0.0558076910674572,
0.02400798164308071,
-0.016805263236165047,
0.021847333759069443,
0.023715779185295105,
-0.021915629506111145,
-0.030765753239393234,
0.0892055332660675,
0.07368690520524979,
0.02283533848822117,
-0.029232600703835487,
0.04234001040458679,
-0.07106691598892212,
-0.0088... | 0.162189 |
`exists` {boolean} Test whether or not the element at the given `path` exists by checking with the file system. Then call the `callback` argument with either true or false: ```mjs import { exists } from 'node:fs'; exists('/etc/passwd', (e) => { console.log(e ? 'it exists' : 'no passwd!'); }); ``` \*\*The parameters for this callback are not consistent with other Node.js callbacks.\*\* Normally, the first parameter to a Node.js callback is an `err` parameter, optionally followed by other parameters. The `fs.exists()` callback has only one boolean parameter. This is one reason `fs.access()` is recommended instead of `fs.exists()`. If `path` is a symbolic link, it is followed. Thus, if `path` exists but points to a non-existent element, the callback will receive the value `false`. Using `fs.exists()` to check for the existence of a file before calling `fs.open()`, `fs.readFile()`, or `fs.writeFile()` is not recommended. Doing so introduces a race condition, since other processes may change the file's state between the two calls. Instead, user code should open/read/write the file directly and handle the error raised if the file does not exist. \*\*write (NOT RECOMMENDED)\*\* ```mjs import { exists, open, close } from 'node:fs'; exists('myfile', (e) => { if (e) { console.error('myfile already exists'); } else { open('myfile', 'wx', (err, fd) => { if (err) throw err; try { writeMyData(fd); } finally { close(fd, (err) => { if (err) throw err; }); } }); } }); ``` \*\*write (RECOMMENDED)\*\* ```mjs import { open, close } from 'node:fs'; open('myfile', 'wx', (err, fd) => { if (err) { if (err.code === 'EEXIST') { console.error('myfile already exists'); return; } throw err; } try { writeMyData(fd); } finally { close(fd, (err) => { if (err) throw err; }); } }); ``` \*\*read (NOT RECOMMENDED)\*\* ```mjs import { open, close, exists } from 'node:fs'; exists('myfile', (e) => { if (e) { open('myfile', 'r', (err, fd) => { if (err) throw err; try { readMyData(fd); } finally { close(fd, (err) => { if (err) throw err; }); } }); } else { console.error('myfile does not exist'); } }); ``` \*\*read (RECOMMENDED)\*\* ```mjs import { open, close } from 'node:fs'; open('myfile', 'r', (err, fd) => { if (err) { if (err.code === 'ENOENT') { console.error('myfile does not exist'); return; } throw err; } try { readMyData(fd); } finally { close(fd, (err) => { if (err) throw err; }); } }); ``` The "not recommended" examples above check for existence and then use the file; the "recommended" examples are better because they use the file directly and handle the error, if any. In general, check for the existence of a file only if the file won't be used directly, for example when its existence is a signal from another process. ### `fs.fchmod(fd, mode, callback)` \* `fd` {integer} \* `mode` {string|integer} \* `callback` {Function} \* `err` {Error} Sets the permissions on the file. No arguments other than a possible exception are given to the completion callback. See the POSIX fchmod(2) documentation for more detail. ### `fs.fchown(fd, uid, gid, callback)` \* `fd` {integer} \* `uid` {integer} \* `gid` {integer} \* `callback` {Function} \* `err` {Error} Sets the owner of the file. No arguments other than a possible exception are given to the completion callback. See the POSIX fchown(2) documentation for more detail. ### `fs.fdatasync(fd, callback)` \* `fd` {integer} \* `callback` {Function} \* `err` {Error} Forces all currently queued I/O operations associated with the file to the operating system's synchronized I/O completion state. Refer to the POSIX fdatasync(2) documentation for details. No arguments other than a possible exception are given to the completion callback. ### `fs.fstat(fd[, options], callback)` \* `fd` {integer} \* `options` {Object} \* | https://github.com/nodejs/node/blob/main//doc/api/fs.md | main | nodejs | [
-0.08140747994184494,
-0.003221806138753891,
-0.028663188219070435,
0.07548768073320389,
0.11851882934570312,
-0.06459270417690277,
-0.011618069373071194,
0.03076154924929142,
0.10217040777206421,
-0.009447556920349598,
0.022974489256739616,
0.07837462425231934,
0.03416862338781357,
-0.033... | 0.103784 |
Forces all currently queued I/O operations associated with the file to the operating system's synchronized I/O completion state. Refer to the POSIX fdatasync(2) documentation for details. No arguments other than a possible exception are given to the completion callback. ### `fs.fstat(fd[, options], callback)` \* `fd` {integer} \* `options` {Object} \* `bigint` {boolean} Whether the numeric values in the returned {fs.Stats} object should be `bigint`. \*\*Default:\*\* `false`. \* `callback` {Function} \* `err` {Error} \* `stats` {fs.Stats} Invokes the callback with the {fs.Stats} for the file descriptor. See the POSIX fstat(2) documentation for more detail. ### `fs.fsync(fd, callback)` \* `fd` {integer} \* `callback` {Function} \* `err` {Error} Request that all data for the open file descriptor is flushed to the storage device. The specific implementation is operating system and device specific. Refer to the POSIX fsync(2) documentation for more detail. No arguments other than a possible exception are given to the completion callback. ### `fs.ftruncate(fd[, len], callback)` \* `fd` {integer} \* `len` {integer} \*\*Default:\*\* `0` \* `callback` {Function} \* `err` {Error} Truncates the file descriptor. No arguments other than a possible exception are given to the completion callback. See the POSIX ftruncate(2) documentation for more detail. If the file referred to by the file descriptor was larger than `len` bytes, only the first `len` bytes will be retained in the file. For example, the following program retains only the first four bytes of the file: ```mjs import { open, close, ftruncate } from 'node:fs'; function closeFd(fd) { close(fd, (err) => { if (err) throw err; }); } open('temp.txt', 'r+', (err, fd) => { if (err) throw err; try { ftruncate(fd, 4, (err) => { closeFd(fd); if (err) throw err; }); } catch (err) { closeFd(fd); if (err) throw err; } }); ``` If the file previously was shorter than `len` bytes, it is extended, and the extended part is filled with null bytes (`'\0'`): If `len` is negative then `0` will be used. ### `fs.futimes(fd, atime, mtime, callback)` \* `fd` {integer} \* `atime` {number|string|Date} \* `mtime` {number|string|Date} \* `callback` {Function} \* `err` {Error} Change the file system timestamps of the object referenced by the supplied file descriptor. See [`fs.utimes()`][]. ### `fs.glob(pattern[, options], callback)` \* `pattern` {string|string\[]} \* `options` {Object} \* `cwd` {string|URL} current working directory. \*\*Default:\*\* `process.cwd()` \* `exclude` {Function|string\[]} Function to filter out files/directories or a list of glob patterns to be excluded. If a function is provided, return `true` to exclude the item, `false` to include it. \*\*Default:\*\* `undefined`. \* `withFileTypes` {boolean} `true` if the glob should return paths as Dirents, `false` otherwise. \*\*Default:\*\* `false`. \* `callback` {Function} \* `err` {Error} \* Retrieves the files matching the specified pattern. ```mjs import { glob } from 'node:fs'; glob('\*\*/\*.js', (err, matches) => { if (err) throw err; console.log(matches); }); ``` ```cjs const { glob } = require('node:fs'); glob('\*\*/\*.js', (err, matches) => { if (err) throw err; console.log(matches); }); ``` ### `fs.lchmod(path, mode, callback)` > Stability: 0 - Deprecated \* `path` {string|Buffer|URL} \* `mode` {integer} \* `callback` {Function} \* `err` {Error|AggregateError} Changes the permissions on a symbolic link. No arguments other than a possible exception are given to the completion callback. This method is only implemented on macOS. See the POSIX lchmod(2) documentation for more detail. ### `fs.lchown(path, uid, gid, callback)` \* `path` {string|Buffer|URL} \* `uid` {integer} \* `gid` {integer} \* `callback` {Function} \* `err` {Error} Set the owner of the symbolic link. No arguments other than a possible exception are given to the completion callback. See the POSIX lchown(2) documentation for more detail. ### `fs.lutimes(path, atime, mtime, callback)` \* `path` {string|Buffer|URL} \* `atime` {number|string|Date} \* `mtime` {number|string|Date} \* `callback` {Function} \* `err` | https://github.com/nodejs/node/blob/main//doc/api/fs.md | main | nodejs | [
-0.10019446909427643,
0.048134300857782364,
-0.08425699174404144,
0.027243269607424736,
0.022881044074892998,
-0.11335421353578568,
0.045059580355882645,
0.0868658497929573,
0.07208849489688873,
0.006780246272683144,
-0.012586943805217743,
0.06199540197849274,
-0.06018458679318428,
-0.0258... | 0.163694 |
\* `err` {Error} Set the owner of the symbolic link. No arguments other than a possible exception are given to the completion callback. See the POSIX lchown(2) documentation for more detail. ### `fs.lutimes(path, atime, mtime, callback)` \* `path` {string|Buffer|URL} \* `atime` {number|string|Date} \* `mtime` {number|string|Date} \* `callback` {Function} \* `err` {Error} Changes the access and modification times of a file in the same way as [`fs.utimes()`][], with the difference that if the path refers to a symbolic link, then the link is not dereferenced: instead, the timestamps of the symbolic link itself are changed. No arguments other than a possible exception are given to the completion callback. ### `fs.link(existingPath, newPath, callback)` \* `existingPath` {string|Buffer|URL} \* `newPath` {string|Buffer|URL} \* `callback` {Function} \* `err` {Error} Creates a new link from the `existingPath` to the `newPath`. See the POSIX link(2) documentation for more detail. No arguments other than a possible exception are given to the completion callback. ### `fs.lstat(path[, options], callback)` \* `path` {string|Buffer|URL} \* `options` {Object} \* `bigint` {boolean} Whether the numeric values in the returned {fs.Stats} object should be `bigint`. \*\*Default:\*\* `false`. \* `callback` {Function} \* `err` {Error} \* `stats` {fs.Stats} Retrieves the {fs.Stats} for the symbolic link referred to by the path. The callback gets two arguments `(err, stats)` where `stats` is a {fs.Stats} object. `lstat()` is identical to `stat()`, except that if `path` is a symbolic link, then the link itself is stat-ed, not the file that it refers to. See the POSIX lstat(2) documentation for more details. ### `fs.mkdir(path[, options], callback)` \* `path` {string|Buffer|URL} \* `options` {Object|integer} \* `recursive` {boolean} \*\*Default:\*\* `false` \* `mode` {string|integer} Not supported on Windows. See [File modes][] for more details. \*\*Default:\*\* `0o777`. \* `callback` {Function} \* `err` {Error} \* `path` {string|undefined} Present only if a directory is created with `recursive` set to `true`. Asynchronously creates a directory. The callback is given a possible exception and, if `recursive` is `true`, the first directory path created, `(err[, path])`. `path` can still be `undefined` when `recursive` is `true`, if no directory was created (for instance, if it was previously created). The optional `options` argument can be an integer specifying `mode` (permission and sticky bits), or an object with a `mode` property and a `recursive` property indicating whether parent directories should be created. Calling `fs.mkdir()` when `path` is a directory that exists results in an error only when `recursive` is false. If `recursive` is false and the directory exists, an `EEXIST` error occurs. ```mjs import { mkdir } from 'node:fs'; // Create ./tmp/a/apple, regardless of whether ./tmp and ./tmp/a exist. mkdir('./tmp/a/apple', { recursive: true }, (err) => { if (err) throw err; }); ``` On Windows, using `fs.mkdir()` on the root directory even with recursion will result in an error: ```mjs import { mkdir } from 'node:fs'; mkdir('/', { recursive: true }, (err) => { // => [Error: EPERM: operation not permitted, mkdir 'C:\'] }); ``` See the POSIX mkdir(2) documentation for more details. ### `fs.mkdtemp(prefix[, options], callback)` \* `prefix` {string|Buffer|URL} \* `options` {string|Object} \* `encoding` {string} \*\*Default:\*\* `'utf8'` \* `callback` {Function} \* `err` {Error} \* `directory` {string} Creates a unique temporary directory. Generates six random characters to be appended behind a required `prefix` to create a unique temporary directory. Due to platform inconsistencies, avoid trailing `X` characters in `prefix`. Some platforms, notably the BSDs, can return more than six random characters, and replace trailing `X` characters in `prefix` with random characters. The created directory path is passed as a string to the callback's second parameter. The optional `options` argument can be a string specifying an encoding, or an object with an `encoding` property specifying the character | https://github.com/nodejs/node/blob/main//doc/api/fs.md | main | nodejs | [
-0.06371422857046127,
0.014517591334879398,
-0.030235910788178444,
0.04646753519773483,
0.01742997020483017,
-0.06504366546869278,
0.009102537296712399,
0.14599090814590454,
0.017313919961452484,
0.0003146010567434132,
-0.0027812898624688387,
0.06065751612186432,
-0.01090881135314703,
-0.0... | 0.031347 |
more than six random characters, and replace trailing `X` characters in `prefix` with random characters. The created directory path is passed as a string to the callback's second parameter. The optional `options` argument can be a string specifying an encoding, or an object with an `encoding` property specifying the character encoding to use. ```mjs import { mkdtemp } from 'node:fs'; import { join } from 'node:path'; import { tmpdir } from 'node:os'; mkdtemp(join(tmpdir(), 'foo-'), (err, directory) => { if (err) throw err; console.log(directory); // Prints: /tmp/foo-itXde2 or C:\Users\...\AppData\Local\Temp\foo-itXde2 }); ``` The `fs.mkdtemp()` method will append the six randomly selected characters directly to the `prefix` string. For instance, given a directory `/tmp`, if the intention is to create a temporary directory \_within\_ `/tmp`, the `prefix` must end with a trailing platform-specific path separator (`require('node:path').sep`). ```mjs import { tmpdir } from 'node:os'; import { mkdtemp } from 'node:fs'; // The parent directory for the new temporary directory const tmpDir = tmpdir(); // This method is \*INCORRECT\*: mkdtemp(tmpDir, (err, directory) => { if (err) throw err; console.log(directory); // Will print something similar to `/tmpabc123`. // A new temporary directory is created at the file system root // rather than \*within\* the /tmp directory. }); // This method is \*CORRECT\*: import { sep } from 'node:path'; mkdtemp(`${tmpDir}${sep}`, (err, directory) => { if (err) throw err; console.log(directory); // Will print something similar to `/tmp/abc123`. // A new temporary directory is created within // the /tmp directory. }); ``` ### `fs.open(path[, flags[, mode]], callback)` \* `path` {string|Buffer|URL} \* `flags` {string|number} See [support of file system `flags`][]. \*\*Default:\*\* `'r'`. \* `mode` {string|integer} \*\*Default:\*\* `0o666` (readable and writable) \* `callback` {Function} \* `err` {Error} \* `fd` {integer} Asynchronous file open. See the POSIX open(2) documentation for more details. `mode` sets the file mode (permission and sticky bits), but only if the file was created. On Windows, only the write permission can be manipulated; see [`fs.chmod()`][]. The callback gets two arguments `(err, fd)`. Some characters (`< > : " / \ | ? \*`) are reserved under Windows as documented by [Naming Files, Paths, and Namespaces][]. Under NTFS, if the filename contains a colon, Node.js will open a file system stream, as described by [this MSDN page][MSDN-Using-Streams]. Functions based on `fs.open()` exhibit this behavior as well: `fs.writeFile()`, `fs.readFile()`, etc. ### `fs.openAsBlob(path[, options])` \* `path` {string|Buffer|URL} \* `options` {Object} \* `type` {string} An optional mime type for the blob. \* Returns: {Promise} Fulfills with a {Blob} upon success. Returns a {Blob} whose data is backed by the given file. The file must not be modified after the {Blob} is created. Any modifications will cause reading the {Blob} data to fail with a `DOMException` error. Synchronous stat operations on the file when the `Blob` is created, and before each read in order to detect whether the file data has been modified on disk. ```mjs import { openAsBlob } from 'node:fs'; const blob = await openAsBlob('the.file.txt'); const ab = await blob.arrayBuffer(); blob.stream(); ``` ```cjs const { openAsBlob } = require('node:fs'); (async () => { const blob = await openAsBlob('the.file.txt'); const ab = await blob.arrayBuffer(); blob.stream(); })(); ``` ### `fs.opendir(path[, options], callback)` \* `path` {string|Buffer|URL} \* `options` {Object} \* `encoding` {string|null} \*\*Default:\*\* `'utf8'` \* `bufferSize` {number} Number of directory entries that are buffered internally when reading from the directory. Higher values lead to better performance but higher memory usage. \*\*Default:\*\* `32` \* `recursive` {boolean} \*\*Default:\*\* `false` \* `callback` {Function} \* `err` {Error} \* `dir` {fs.Dir} Asynchronously open a directory. See the POSIX opendir(3) documentation for more details. Creates an {fs.Dir}, which contains all further functions for reading from and cleaning up the directory. | https://github.com/nodejs/node/blob/main//doc/api/fs.md | main | nodejs | [
0.0013122892705723643,
-0.025553708896040916,
0.01281044166535139,
0.045816820114851,
-0.005609764251857996,
-0.043576210737228394,
0.014586595818400383,
0.07059700042009354,
0.06967131048440933,
0.012749587185680866,
0.057518552988767624,
-0.02378040738403797,
0.03356713429093361,
-0.0201... | 0.070563 |
better performance but higher memory usage. \*\*Default:\*\* `32` \* `recursive` {boolean} \*\*Default:\*\* `false` \* `callback` {Function} \* `err` {Error} \* `dir` {fs.Dir} Asynchronously open a directory. See the POSIX opendir(3) documentation for more details. Creates an {fs.Dir}, which contains all further functions for reading from and cleaning up the directory. The `encoding` option sets the encoding for the `path` while opening the directory and subsequent read operations. ### `fs.read(fd, buffer, offset, length, position, callback)` \* `fd` {integer} \* `buffer` {Buffer|TypedArray|DataView} The buffer that the data will be written to. \* `offset` {integer} The position in `buffer` to write the data to. \* `length` {integer} The number of bytes to read. \* `position` {integer|bigint|null} Specifies where to begin reading from in the file. If `position` is `null` or `-1 `, data will be read from the current file position, and the file position will be updated. If `position` is a non-negative integer, the file position will be unchanged. \* `callback` {Function} \* `err` {Error} \* `bytesRead` {integer} \* `buffer` {Buffer} Read data from the file specified by `fd`. The callback is given the three arguments, `(err, bytesRead, buffer)`. If the file is not modified concurrently, the end-of-file is reached when the number of bytes read is zero. If this method is invoked as its [`util.promisify()`][]ed version, it returns a promise for an `Object` with `bytesRead` and `buffer` properties. The `fs.read()` method reads data from the file specified by the file descriptor (`fd`). The `length` argument indicates the maximum number of bytes that Node.js will attempt to read from the kernel. However, the actual number of bytes read (`bytesRead`) can be lower than the specified `length` for various reasons. For example: \* If the file is shorter than the specified `length`, `bytesRead` will be set to the actual number of bytes read. \* If the file encounters EOF (End of File) before the buffer could be filled, Node.js will read all available bytes until EOF is encountered, and the `bytesRead` parameter in the callback will indicate the actual number of bytes read, which may be less than the specified `length`. \* If the file is on a slow network `filesystem` or encounters any other issue during reading, `bytesRead` can be lower than the specified `length`. Therefore, when using `fs.read()`, it's important to check the `bytesRead` value to determine how many bytes were actually read from the file. Depending on your application logic, you may need to handle cases where `bytesRead` is lower than the specified `length`, such as by wrapping the read call in a loop if you require a minimum amount of bytes. This behavior is similar to the POSIX `preadv2` function. ### `fs.read(fd[, options], callback)` \* `fd` {integer} \* `options` {Object} \* `buffer` {Buffer|TypedArray|DataView} \*\*Default:\*\* `Buffer.alloc(16384)` \* `offset` {integer} \*\*Default:\*\* `0` \* `length` {integer} \*\*Default:\*\* `buffer.byteLength - offset` \* `position` {integer|bigint|null} \*\*Default:\*\* `null` \* `callback` {Function} \* `err` {Error} \* `bytesRead` {integer} \* `buffer` {Buffer} Similar to the [`fs.read()`][] function, this version takes an optional `options` object. If no `options` object is specified, it will default with the above values. ### `fs.read(fd, buffer[, options], callback)` \* `fd` {integer} \* `buffer` {Buffer|TypedArray|DataView} The buffer that the data will be written to. \* `options` {Object} \* `offset` {integer} \*\*Default:\*\* `0` \* `length` {integer} \*\*Default:\*\* `buffer.byteLength - offset` \* `position` {integer|bigint} \*\*Default:\*\* `null` \* `callback` {Function} \* `err` {Error} \* `bytesRead` {integer} \* `buffer` {Buffer} Similar to the [`fs.read()`][] function, this version takes an optional `options` object. If no `options` object is specified, it will default with the above values. ### `fs.readdir(path[, options], callback)` \* `path` {string|Buffer|URL} \* `options` {string|Object} \* `encoding` {string} | https://github.com/nodejs/node/blob/main//doc/api/fs.md | main | nodejs | [
-0.016347631812095642,
0.005416745785623789,
-0.076925128698349,
0.019248222932219505,
-0.049197107553482056,
-0.10864047706127167,
0.029375309124588966,
0.13370653986930847,
0.06529717892408371,
-0.023259349167346954,
0.013984344899654388,
0.09745404124259949,
0.002207433804869652,
-0.012... | 0.070483 |
\* `callback` {Function} \* `err` {Error} \* `bytesRead` {integer} \* `buffer` {Buffer} Similar to the [`fs.read()`][] function, this version takes an optional `options` object. If no `options` object is specified, it will default with the above values. ### `fs.readdir(path[, options], callback)` \* `path` {string|Buffer|URL} \* `options` {string|Object} \* `encoding` {string} \*\*Default:\*\* `'utf8'` \* `withFileTypes` {boolean} \*\*Default:\*\* `false` \* `recursive` {boolean} If `true`, reads the contents of a directory recursively. In recursive mode, it will list all files, sub files and directories. \*\*Default:\*\* `false`. \* `callback` {Function} \* `err` {Error} \* `files` {string\[]|Buffer\[]|fs.Dirent\[]} Reads the contents of a directory. The callback gets two arguments `(err, files)` where `files` is an array of the names of the files in the directory excluding `'.'` and `'..'`. See the POSIX readdir(3) documentation for more details. The optional `options` argument can be a string specifying an encoding, or an object with an `encoding` property specifying the character encoding to use for the filenames passed to the callback. If the `encoding` is set to `'buffer'`, the filenames returned will be passed as {Buffer} objects. If `options.withFileTypes` is set to `true`, the `files` array will contain {fs.Dirent} objects. ### `fs.readFile(path[, options], callback)` \* `path` {string|Buffer|URL|integer} filename or file descriptor \* `options` {Object|string} \* `encoding` {string|null} \*\*Default:\*\* `null` \* `flag` {string} See [support of file system `flags`][]. \*\*Default:\*\* `'r'`. \* `signal` {AbortSignal} allows aborting an in-progress readFile \* `callback` {Function} \* `err` {Error|AggregateError} \* `data` {string|Buffer} Asynchronously reads the entire contents of a file. ```mjs import { readFile } from 'node:fs'; readFile('/etc/passwd', (err, data) => { if (err) throw err; console.log(data); }); ``` The callback is passed two arguments `(err, data)`, where `data` is the contents of the file. If no encoding is specified, then the raw buffer is returned. If `options` is a string, then it specifies the encoding: ```mjs import { readFile } from 'node:fs'; readFile('/etc/passwd', 'utf8', callback); ``` When the path is a directory, the behavior of `fs.readFile()` and [`fs.readFileSync()`][] is platform-specific. On macOS, Linux, and Windows, an error will be returned. On FreeBSD, a representation of the directory's contents will be returned. ```mjs import { readFile } from 'node:fs'; // macOS, Linux, and Windows readFile('', (err, data) => { // => [Error: EISDIR: illegal operation on a directory, read ] }); // FreeBSD readFile('', (err, data) => { // => null, }); ``` It is possible to abort an ongoing request using an `AbortSignal`. If a request is aborted the callback is called with an `AbortError`: ```mjs import { readFile } from 'node:fs'; const controller = new AbortController(); const signal = controller.signal; readFile(fileInfo[0].name, { signal }, (err, buf) => { // ... }); // When you want to abort the request controller.abort(); ``` The `fs.readFile()` function buffers the entire file. To minimize memory costs, when possible prefer streaming via `fs.createReadStream()`. Aborting an ongoing request does not abort individual operating system requests but rather the internal buffering `fs.readFile` performs. #### File descriptors 1. Any specified file descriptor has to support reading. 2. If a file descriptor is specified as the `path`, it will not be closed automatically. 3. The reading will begin at the current position. For example, if the file already had `'Hello World'` and six bytes are read with the file descriptor, the call to `fs.readFile()` with the same file descriptor, would give `'World'`, rather than `'Hello World'`. #### Performance Considerations The `fs.readFile()` method asynchronously reads the contents of a file into memory one chunk at a time, allowing the event loop to turn between each chunk. This allows the read operation to have less impact on other activity that may be using | https://github.com/nodejs/node/blob/main//doc/api/fs.md | main | nodejs | [
-0.051725130528211594,
-0.0015966234495863318,
-0.07137305289506912,
0.030358348041772842,
-0.04303300008177757,
-0.09446736425161362,
0.060925502330064774,
0.11198212206363678,
0.04564734920859337,
-0.010324540548026562,
0.012635421007871628,
0.039522916078567505,
-0.011824208311736584,
0... | 0.08427 |
`'World'`, rather than `'Hello World'`. #### Performance Considerations The `fs.readFile()` method asynchronously reads the contents of a file into memory one chunk at a time, allowing the event loop to turn between each chunk. This allows the read operation to have less impact on other activity that may be using the underlying libuv thread pool but means that it will take longer to read a complete file into memory. The additional read overhead can vary broadly on different systems and depends on the type of file being read. If the file type is not a regular file (a pipe for instance) and Node.js is unable to determine an actual file size, each read operation will load on 64 KiB of data. For regular files, each read will process 512 KiB of data. For applications that require as-fast-as-possible reading of file contents, it is better to use `fs.read()` directly and for application code to manage reading the full contents of the file itself. The Node.js GitHub issue [#25741][] provides more information and a detailed analysis on the performance of `fs.readFile()` for multiple file sizes in different Node.js versions. ### `fs.readlink(path[, options], callback)` \* `path` {string|Buffer|URL} \* `options` {string|Object} \* `encoding` {string} \*\*Default:\*\* `'utf8'` \* `callback` {Function} \* `err` {Error} \* `linkString` {string|Buffer} Reads the contents of the symbolic link referred to by `path`. The callback gets two arguments `(err, linkString)`. See the POSIX readlink(2) documentation for more details. The optional `options` argument can be a string specifying an encoding, or an object with an `encoding` property specifying the character encoding to use for the link path passed to the callback. If the `encoding` is set to `'buffer'`, the link path returned will be passed as a {Buffer} object. ### `fs.readv(fd, buffers[, position], callback)` \* `fd` {integer} \* `buffers` {ArrayBufferView\[]} \* `position` {integer|null} \*\*Default:\*\* `null` \* `callback` {Function} \* `err` {Error} \* `bytesRead` {integer} \* `buffers` {ArrayBufferView\[]} Read from a file specified by `fd` and write to an array of `ArrayBufferView`s using `readv()`. `position` is the offset from the beginning of the file from where data should be read. If `typeof position !== 'number'`, the data will be read from the current position. The callback will be given three arguments: `err`, `bytesRead`, and `buffers`. `bytesRead` is how many bytes were read from the file. If this method is invoked as its [`util.promisify()`][]ed version, it returns a promise for an `Object` with `bytesRead` and `buffers` properties. ### `fs.realpath(path[, options], callback)` \* `path` {string|Buffer|URL} \* `options` {string|Object} \* `encoding` {string} \*\*Default:\*\* `'utf8'` \* `callback` {Function} \* `err` {Error} \* `resolvedPath` {string|Buffer} Asynchronously computes the canonical pathname by resolving `.`, `..`, and symbolic links. A canonical pathname is not necessarily unique. Hard links and bind mounts can expose a file system entity through many pathnames. This function behaves like realpath(3), with some exceptions: 1. No case conversion is performed on case-insensitive file systems. 2. The maximum number of symbolic links is platform-independent and generally (much) higher than what the native realpath(3) implementation supports. The `callback` gets two arguments `(err, resolvedPath)`. May use `process.cwd` to resolve relative paths. Only paths that can be converted to UTF8 strings are supported. The optional `options` argument can be a string specifying an encoding, or an object with an `encoding` property specifying the character encoding to use for the path passed to the callback. If the `encoding` is set to `'buffer'`, the path returned will be passed as a {Buffer} object. If `path` resolves to a socket or a pipe, the function will return a system dependent name for that object. A path that does not exist results in an | https://github.com/nodejs/node/blob/main//doc/api/fs.md | main | nodejs | [
-0.0028304425068199635,
0.007932957261800766,
-0.033186182379722595,
0.04128639027476311,
0.09927982091903687,
-0.0905543640255928,
-0.031169552356004715,
0.10999546945095062,
0.07488773763179779,
0.02359795942902565,
-0.061115093529224396,
0.1307455599308014,
-0.08930868655443192,
-0.0624... | 0.078752 |
passed to the callback. If the `encoding` is set to `'buffer'`, the path returned will be passed as a {Buffer} object. If `path` resolves to a socket or a pipe, the function will return a system dependent name for that object. A path that does not exist results in an ENOENT error. `error.path` is the absolute file path. ### `fs.realpath.native(path[, options], callback)` \* `path` {string|Buffer|URL} \* `options` {string|Object} \* `encoding` {string} \*\*Default:\*\* `'utf8'` \* `callback` {Function} \* `err` {Error} \* `resolvedPath` {string|Buffer} Asynchronous realpath(3). The `callback` gets two arguments `(err, resolvedPath)`. Only paths that can be converted to UTF8 strings are supported. The optional `options` argument can be a string specifying an encoding, or an object with an `encoding` property specifying the character encoding to use for the path passed to the callback. If the `encoding` is set to `'buffer'`, the path returned will be passed as a {Buffer} object. On Linux, when Node.js is linked against musl libc, the procfs file system must be mounted on `/proc` in order for this function to work. Glibc does not have this restriction. ### `fs.rename(oldPath, newPath, callback)` \* `oldPath` {string|Buffer|URL} \* `newPath` {string|Buffer|URL} \* `callback` {Function} \* `err` {Error} Asynchronously rename file at `oldPath` to the pathname provided as `newPath`. In the case that `newPath` already exists, it will be overwritten. If there is a directory at `newPath`, an error will be raised instead. No arguments other than a possible exception are given to the completion callback. See also: rename(2). ```mjs import { rename } from 'node:fs'; rename('oldFile.txt', 'newFile.txt', (err) => { if (err) throw err; console.log('Rename complete!'); }); ``` ### `fs.rmdir(path[, options], callback)` \* `path` {string|Buffer|URL} \* `options` {Object} There are currently no options exposed. There used to be options for `recursive`, `maxBusyTries`, and `emfileWait` but they were deprecated and removed. The `options` argument is still accepted for backwards compatibility but it is not used. \* `callback` {Function} \* `err` {Error} Asynchronous rmdir(2). No arguments other than a possible exception are given to the completion callback. Using `fs.rmdir()` on a file (not a directory) results in an `ENOENT` error on Windows and an `ENOTDIR` error on POSIX. To get a behavior similar to the `rm -rf` Unix command, use [`fs.rm()`][] with options `{ recursive: true, force: true }`. ### `fs.rm(path[, options], callback)` \* `path` {string|Buffer|URL} \* `options` {Object} \* `force` {boolean} When `true`, exceptions will be ignored if `path` does not exist. \*\*Default:\*\* `false`. \* `maxRetries` {integer} If an `EBUSY`, `EMFILE`, `ENFILE`, `ENOTEMPTY`, or `EPERM` error is encountered, Node.js will retry the operation with a linear backoff wait of `retryDelay` milliseconds longer on each try. This option represents the number of retries. This option is ignored if the `recursive` option is not `true`. \*\*Default:\*\* `0`. \* `recursive` {boolean} If `true`, perform a recursive removal. In recursive mode operations are retried on failure. \*\*Default:\*\* `false`. \* `retryDelay` {integer} The amount of time in milliseconds to wait between retries. This option is ignored if the `recursive` option is not `true`. \*\*Default:\*\* `100`. \* `callback` {Function} \* `err` {Error} Asynchronously removes files and directories (modeled on the standard POSIX `rm` utility). No arguments other than a possible exception are given to the completion callback. ### `fs.stat(path[, options], callback)` \* `path` {string|Buffer|URL} \* `options` {Object} \* `bigint` {boolean} Whether the numeric values in the returned {fs.Stats} object should be `bigint`. \*\*Default:\*\* `false`. \* `callback` {Function} \* `err` {Error} \* `stats` {fs.Stats} Asynchronous stat(2). The callback gets two arguments `(err, stats)` where `stats` is an {fs.Stats} object. In case of an error, the `err.code` will be one of [Common System Errors][]. [`fs.stat()`][] follows symbolic links. Use | https://github.com/nodejs/node/blob/main//doc/api/fs.md | main | nodejs | [
-0.06519141048192978,
-0.028805460780858994,
-0.09406978636980057,
0.05321982130408287,
-0.063890241086483,
-0.056847382336854935,
0.0017042983090505004,
0.08959425985813141,
0.06299670785665512,
-0.05780617147684097,
-0.03321011736989021,
0.020779261365532875,
-0.05243458226323128,
0.0556... | 0.07783 |
{fs.Stats} object should be `bigint`. \*\*Default:\*\* `false`. \* `callback` {Function} \* `err` {Error} \* `stats` {fs.Stats} Asynchronous stat(2). The callback gets two arguments `(err, stats)` where `stats` is an {fs.Stats} object. In case of an error, the `err.code` will be one of [Common System Errors][]. [`fs.stat()`][] follows symbolic links. Use [`fs.lstat()`][] to look at the links themselves. Using `fs.stat()` to check for the existence of a file before calling `fs.open()`, `fs.readFile()`, or `fs.writeFile()` is not recommended. Instead, user code should open/read/write the file directly and handle the error raised if the file is not available. To check if a file exists without manipulating it afterwards, [`fs.access()`][] is recommended. For example, given the following directory structure: ```text - txtDir -- file.txt - app.js ``` The next program will check for the stats of the given paths: ```mjs import { stat } from 'node:fs'; const pathsToCheck = ['./txtDir', './txtDir/file.txt']; for (let i = 0; i < pathsToCheck.length; i++) { stat(pathsToCheck[i], (err, stats) => { console.log(stats.isDirectory()); console.log(stats); }); } ``` The resulting output will resemble: ```console true Stats { dev: 16777220, mode: 16877, nlink: 3, uid: 501, gid: 20, rdev: 0, blksize: 4096, ino: 14214262, size: 96, blocks: 0, atimeMs: 1561174653071.963, mtimeMs: 1561174614583.3518, ctimeMs: 1561174626623.5366, birthtimeMs: 1561174126937.2893, atime: 2019-06-22T03:37:33.072Z, mtime: 2019-06-22T03:36:54.583Z, ctime: 2019-06-22T03:37:06.624Z, birthtime: 2019-06-22T03:28:46.937Z } false Stats { dev: 16777220, mode: 33188, nlink: 1, uid: 501, gid: 20, rdev: 0, blksize: 4096, ino: 14214074, size: 8, blocks: 8, atimeMs: 1561174616618.8555, mtimeMs: 1561174614584, ctimeMs: 1561174614583.8145, birthtimeMs: 1561174007710.7478, atime: 2019-06-22T03:36:56.619Z, mtime: 2019-06-22T03:36:54.584Z, ctime: 2019-06-22T03:36:54.584Z, birthtime: 2019-06-22T03:26:47.711Z } ``` ### `fs.statfs(path[, options], callback)` \* `path` {string|Buffer|URL} \* `options` {Object} \* `bigint` {boolean} Whether the numeric values in the returned {fs.StatFs} object should be `bigint`. \*\*Default:\*\* `false`. \* `callback` {Function} \* `err` {Error} \* `stats` {fs.StatFs} Asynchronous statfs(2). Returns information about the mounted file system which contains `path`. The callback gets two arguments `(err, stats)` where `stats` is an {fs.StatFs} object. In case of an error, the `err.code` will be one of [Common System Errors][]. ### `fs.symlink(target, path[, type], callback)` \* `target` {string|Buffer|URL} \* `path` {string|Buffer|URL} \* `type` {string|null} \*\*Default:\*\* `null` \* `callback` {Function} \* `err` {Error} Creates the link called `path` pointing to `target`. No arguments other than a possible exception are given to the completion callback. See the POSIX symlink(2) documentation for more details. The `type` argument is only available on Windows and ignored on other platforms. It can be set to `'dir'`, `'file'`, or `'junction'`. If the `type` argument is `null`, Node.js will autodetect `target` type and use `'file'` or `'dir'`. If the `target` does not exist, `'file'` will be used. Windows junction points require the destination path to be absolute. When using `'junction'`, the `target` argument will automatically be normalized to absolute path. Junction points on NTFS volumes can only point to directories. Relative targets are relative to the link's parent directory. ```mjs import { symlink } from 'node:fs'; symlink('./mew', './mewtwo', callback); ``` The above example creates a symbolic link `mewtwo` which points to `mew` in the same directory: ```bash $ tree . . ├── mew └── mewtwo -> ./mew ``` ### `fs.truncate(path[, len], callback)` \* `path` {string|Buffer|URL} \* `len` {integer} \*\*Default:\*\* `0` \* `callback` {Function} \* `err` {Error|AggregateError} Truncates the file. No arguments other than a possible exception are given to the completion callback. A file descriptor can also be passed as the first argument. In this case, `fs.ftruncate()` is called. ```mjs import { truncate } from 'node:fs'; // Assuming that 'path/file.txt' is a regular file. truncate('path/file.txt', (err) => { if (err) throw err; console.log('path/file.txt was truncated'); }); ``` ```cjs const { truncate } = require('node:fs'); // Assuming that 'path/file.txt' is | https://github.com/nodejs/node/blob/main//doc/api/fs.md | main | nodejs | [
-0.08283668011426926,
0.047332990914583206,
-0.1299934685230255,
0.08403085172176361,
0.08499569445848465,
-0.09306126832962036,
-0.011638656258583069,
0.18170680105686188,
0.0036873132921755314,
0.0186702162027359,
-0.03355879709124565,
0.05107925459742546,
0.01559293083846569,
-0.0503344... | 0.107602 |
as the first argument. In this case, `fs.ftruncate()` is called. ```mjs import { truncate } from 'node:fs'; // Assuming that 'path/file.txt' is a regular file. truncate('path/file.txt', (err) => { if (err) throw err; console.log('path/file.txt was truncated'); }); ``` ```cjs const { truncate } = require('node:fs'); // Assuming that 'path/file.txt' is a regular file. truncate('path/file.txt', (err) => { if (err) throw err; console.log('path/file.txt was truncated'); }); ``` Passing a file descriptor is deprecated and may result in an error being thrown in the future. See the POSIX truncate(2) documentation for more details. ### `fs.unlink(path, callback)` \* `path` {string|Buffer|URL} \* `callback` {Function} \* `err` {Error} Asynchronously removes a file or symbolic link. No arguments other than a possible exception are given to the completion callback. ```mjs import { unlink } from 'node:fs'; // Assuming that 'path/file.txt' is a regular file. unlink('path/file.txt', (err) => { if (err) throw err; console.log('path/file.txt was deleted'); }); ``` `fs.unlink()` will not work on a directory, empty or otherwise. To remove a directory, use [`fs.rmdir()`][]. See the POSIX unlink(2) documentation for more details. ### `fs.unwatchFile(filename[, listener])` \* `filename` {string|Buffer|URL} \* `listener` {Function} Optional, a listener previously attached using `fs.watchFile()` Stop watching for changes on `filename`. If `listener` is specified, only that particular listener is removed. Otherwise, \_all\_ listeners are removed, effectively stopping watching of `filename`. Calling `fs.unwatchFile()` with a filename that is not being watched is a no-op, not an error. Using [`fs.watch()`][] is more efficient than `fs.watchFile()` and `fs.unwatchFile()`. `fs.watch()` should be used instead of `fs.watchFile()` and `fs.unwatchFile()` when possible. ### `fs.utimes(path, atime, mtime, callback)` \* `path` {string|Buffer|URL} \* `atime` {number|string|Date} \* `mtime` {number|string|Date} \* `callback` {Function} \* `err` {Error} Change the file system timestamps of the object referenced by `path`. The `atime` and `mtime` arguments follow these rules: \* Values can be either numbers representing Unix epoch time in seconds, `Date`s, or a numeric string like `'123456789.0'`. \* If the value can not be converted to a number, or is `NaN`, `Infinity`, or `-Infinity`, an `Error` will be thrown. ### `fs.watch(filename[, options][, listener])` \* `filename` {string|Buffer|URL} \* `options` {string|Object} \* `persistent` {boolean} Indicates whether the process should continue to run as long as files are being watched. \*\*Default:\*\* `true`. \* `recursive` {boolean} Indicates whether all subdirectories should be watched, or only the current directory. This applies when a directory is specified, and only on supported platforms (See [caveats][]). \*\*Default:\*\* `false`. \* `encoding` {string} Specifies the character encoding to be used for the filename passed to the listener. \*\*Default:\*\* `'utf8'`. \* `signal` {AbortSignal} allows closing the watcher with an AbortSignal. \* `ignore` {string|RegExp|Function|Array} Pattern(s) to ignore. Strings are glob patterns (using [`minimatch`][]), RegExp patterns are tested against the filename, and functions receive the filename and return `true` to ignore. \*\*Default:\*\* `undefined`. \* `listener` {Function|undefined} \*\*Default:\*\* `undefined` \* `eventType` {string} \* `filename` {string|Buffer|null} \* Returns: {fs.FSWatcher} Watch for changes on `filename`, where `filename` is either a file or a directory. The second argument is optional. If `options` is provided as a string, it specifies the `encoding`. Otherwise `options` should be passed as an object. The listener callback gets two arguments `(eventType, filename)`. `eventType` is either `'rename'` or `'change'`, and `filename` is the name of the file which triggered the event. On most platforms, `'rename'` is emitted whenever a filename appears or disappears in the directory. The listener callback is attached to the `'change'` event fired by {fs.FSWatcher}, but it is not the same thing as the `'change'` value of `eventType`. If a `signal` is passed, aborting the corresponding AbortController will close the returned {fs.FSWatcher}. #### Caveats The `fs.watch` API is not 100% consistent across platforms, and is unavailable | https://github.com/nodejs/node/blob/main//doc/api/fs.md | main | nodejs | [
-0.04227515310049057,
0.10417000949382782,
-0.000620214850641787,
0.05167094245553017,
0.05698126181960106,
-0.06672003120183945,
0.02074342593550682,
0.13744792342185974,
0.04135478660464287,
0.019538793712854385,
0.012514762580394745,
0.13056634366512299,
-0.06086684390902519,
-0.0185414... | 0.143372 |
is attached to the `'change'` event fired by {fs.FSWatcher}, but it is not the same thing as the `'change'` value of `eventType`. If a `signal` is passed, aborting the corresponding AbortController will close the returned {fs.FSWatcher}. #### Caveats The `fs.watch` API is not 100% consistent across platforms, and is unavailable in some situations. On Windows, no events will be emitted if the watched directory is moved or renamed. An `EPERM` error is reported when the watched directory is deleted. The `fs.watch` API does not provide any protection with respect to malicious actions on the file system. For example, on Windows it is implemented by monitoring changes in a directory versus specific files. This allows substitution of a file and fs reporting changes on the new file with the same filename. ##### Availability This feature depends on the underlying operating system providing a way to be notified of file system changes. \* On Linux systems, this uses [`inotify(7)`][]. \* On BSD systems, this uses [`kqueue(2)`][]. \* On macOS, this uses [`kqueue(2)`][] for files and [`FSEvents`][] for directories. \* On SunOS systems (including Solaris and SmartOS), this uses [`event ports`][]. \* On Windows systems, this feature depends on [`ReadDirectoryChangesW`][]. \* On AIX systems, this feature depends on [`AHAFS`][], which must be enabled. \* On IBM i systems, this feature is not supported. If the underlying functionality is not available for some reason, then `fs.watch()` will not be able to function and may throw an exception. For example, watching files or directories can be unreliable, and in some cases impossible, on network file systems (NFS, SMB, etc) or host file systems when using virtualization software such as Vagrant or Docker. It is still possible to use `fs.watchFile()`, which uses stat polling, but this method is slower and less reliable. ##### Inodes On Linux and macOS systems, `fs.watch()` resolves the path to an [inode][] and watches the inode. If the watched path is deleted and recreated, it is assigned a new inode. The watch will emit an event for the delete but will continue watching the \_original\_ inode. Events for the new inode will not be emitted. This is expected behavior. AIX files retain the same inode for the lifetime of a file. Saving and closing a watched file on AIX will result in two notifications (one for adding new content, and one for truncation). ##### Filename argument Providing `filename` argument in the callback is only supported on Linux, macOS, Windows, and AIX. Even on supported platforms, `filename` is not always guaranteed to be provided. Therefore, don't assume that `filename` argument is always provided in the callback, and have some fallback logic if it is `null`. ```mjs import { watch } from 'node:fs'; watch('somedir', (eventType, filename) => { console.log(`event type is: ${eventType}`); if (filename) { console.log(`filename provided: ${filename}`); } else { console.log('filename not provided'); } }); ``` ### `fs.watchFile(filename[, options], listener)` \* `filename` {string|Buffer|URL} \* `options` {Object} \* `bigint` {boolean} \*\*Default:\*\* `false` \* `persistent` {boolean} \*\*Default:\*\* `true` \* `interval` {integer} \*\*Default:\*\* `5007` \* `listener` {Function} \* `current` {fs.Stats} \* `previous` {fs.Stats} \* Returns: {fs.StatWatcher} Watch for changes on `filename`. The callback `listener` will be called each time the file is accessed. The `options` argument may be omitted. If provided, it should be an object. The `options` object may contain a boolean named `persistent` that indicates whether the process should continue to run as long as files are being watched. The `options` object may specify an `interval` property indicating how often the target should be polled in milliseconds. The `listener` gets two arguments the current stat object and the previous stat object: ```mjs import { | https://github.com/nodejs/node/blob/main//doc/api/fs.md | main | nodejs | [
-0.05737937241792679,
-0.027639271691441536,
-0.07528458535671234,
0.028377259150147438,
0.19013933837413788,
0.03658216446638107,
0.03913111612200737,
0.06698747724294662,
0.13375575840473175,
0.07524804770946503,
0.010481465607881546,
0.057407964020967484,
-0.01832984946668148,
-0.051220... | 0.163166 |
indicates whether the process should continue to run as long as files are being watched. The `options` object may specify an `interval` property indicating how often the target should be polled in milliseconds. The `listener` gets two arguments the current stat object and the previous stat object: ```mjs import { watchFile } from 'node:fs'; watchFile('message.text', (curr, prev) => { console.log(`the current mtime is: ${curr.mtime}`); console.log(`the previous mtime was: ${prev.mtime}`); }); ``` These stat objects are instances of `fs.Stat`. If the `bigint` option is `true`, the numeric values in these objects are specified as `BigInt`s. To be notified when the file was modified, not just accessed, it is necessary to compare `curr.mtimeMs` and `prev.mtimeMs`. When an `fs.watchFile` operation results in an `ENOENT` error, it will invoke the listener once, with all the fields zeroed (or, for dates, the Unix Epoch). If the file is created later on, the listener will be called again, with the latest stat objects. This is a change in functionality since v0.10. Using [`fs.watch()`][] is more efficient than `fs.watchFile` and `fs.unwatchFile`. `fs.watch` should be used instead of `fs.watchFile` and `fs.unwatchFile` when possible. When a file being watched by `fs.watchFile()` disappears and reappears, then the contents of `previous` in the second callback event (the file's reappearance) will be the same as the contents of `previous` in the first callback event (its disappearance). This happens when: \* the file is deleted, followed by a restore \* the file is renamed and then renamed a second time back to its original name ### `fs.write(fd, buffer, offset[, length[, position]], callback)` \* `fd` {integer} \* `buffer` {Buffer|TypedArray|DataView} \* `offset` {integer} \*\*Default:\*\* `0` \* `length` {integer} \*\*Default:\*\* `buffer.byteLength - offset` \* `position` {integer|null} \*\*Default:\*\* `null` \* `callback` {Function} \* `err` {Error} \* `bytesWritten` {integer} \* `buffer` {Buffer|TypedArray|DataView} Write `buffer` to the file specified by `fd`. `offset` determines the part of the buffer to be written, and `length` is an integer specifying the number of bytes to write. `position` refers to the offset from the beginning of the file where this data should be written. If `typeof position !== 'number'`, the data will be written at the current position. See pwrite(2). The callback will be given three arguments `(err, bytesWritten, buffer)` where `bytesWritten` specifies how many \_bytes\_ were written from `buffer`. If this method is invoked as its [`util.promisify()`][]ed version, it returns a promise for an `Object` with `bytesWritten` and `buffer` properties. It is unsafe to use `fs.write()` multiple times on the same file without waiting for the callback. For this scenario, [`fs.createWriteStream()`][] is recommended. On Linux, positional writes don't work when the file is opened in append mode. The kernel ignores the position argument and always appends the data to the end of the file. ### `fs.write(fd, buffer[, options], callback)` \* `fd` {integer} \* `buffer` {Buffer|TypedArray|DataView} \* `options` {Object} \* `offset` {integer} \*\*Default:\*\* `0` \* `length` {integer} \*\*Default:\*\* `buffer.byteLength - offset` \* `position` {integer|null} \*\*Default:\*\* `null` \* `callback` {Function} \* `err` {Error} \* `bytesWritten` {integer} \* `buffer` {Buffer|TypedArray|DataView} Write `buffer` to the file specified by `fd`. Similar to the above `fs.write` function, this version takes an optional `options` object. If no `options` object is specified, it will default with the above values. ### `fs.write(fd, string[, position[, encoding]], callback)` \* `fd` {integer} \* `string` {string} \* `position` {integer|null} \*\*Default:\*\* `null` \* `encoding` {string} \*\*Default:\*\* `'utf8'` \* `callback` {Function} \* `err` {Error} \* `written` {integer} \* `string` {string} Write `string` to the file specified by `fd`. If `string` is not a string, an exception is thrown. `position` refers to the offset from the beginning of the file where this data should be written. If `typeof | https://github.com/nodejs/node/blob/main//doc/api/fs.md | main | nodejs | [
-0.02383933775126934,
0.011341116391122341,
-0.020600592717528343,
0.07326880842447281,
0.1330866515636444,
-0.022103795781731606,
0.04382271319627762,
0.08598598092794418,
0.11962784081697464,
0.03992224112153053,
-0.04683701694011688,
0.04790226370096207,
-0.026266105473041534,
-0.067397... | 0.159143 |
`'utf8'` \* `callback` {Function} \* `err` {Error} \* `written` {integer} \* `string` {string} Write `string` to the file specified by `fd`. If `string` is not a string, an exception is thrown. `position` refers to the offset from the beginning of the file where this data should be written. If `typeof position !== 'number'` the data will be written at the current position. See pwrite(2). `encoding` is the expected string encoding. The callback will receive the arguments `(err, written, string)` where `written` specifies how many \_bytes\_ the passed string required to be written. Bytes written is not necessarily the same as string characters written. See [`Buffer.byteLength`][]. It is unsafe to use `fs.write()` multiple times on the same file without waiting for the callback. For this scenario, [`fs.createWriteStream()`][] is recommended. On Linux, positional writes don't work when the file is opened in append mode. The kernel ignores the position argument and always appends the data to the end of the file. On Windows, if the file descriptor is connected to the console (e.g. `fd == 1` or `stdout`) a string containing non-ASCII characters will not be rendered properly by default, regardless of the encoding used. It is possible to configure the console to render UTF-8 properly by changing the active codepage with the `chcp 65001` command. See the [chcp][] docs for more details. ### `fs.writeFile(file, data[, options], callback)` \* `file` {string|Buffer|URL|integer} filename or file descriptor \* `data` {string|Buffer|TypedArray|DataView} \* `options` {Object|string} \* `encoding` {string|null} \*\*Default:\*\* `'utf8'` \* `mode` {integer} \*\*Default:\*\* `0o666` \* `flag` {string} See [support of file system `flags`][]. \*\*Default:\*\* `'w'`. \* `flush` {boolean} If all data is successfully written to the file, and `flush` is `true`, `fs.fsync()` is used to flush the data. \*\*Default:\*\* `false`. \* `signal` {AbortSignal} allows aborting an in-progress writeFile \* `callback` {Function} \* `err` {Error|AggregateError} When `file` is a filename, asynchronously writes data to the file, replacing the file if it already exists. `data` can be a string or a buffer. When `file` is a file descriptor, the behavior is similar to calling `fs.write()` directly (which is recommended). See the notes below on using a file descriptor. The `encoding` option is ignored if `data` is a buffer. The `mode` option only affects the newly created file. See [`fs.open()`][] for more details. ```mjs import { writeFile } from 'node:fs'; import { Buffer } from 'node:buffer'; const data = new Uint8Array(Buffer.from('Hello Node.js')); writeFile('message.txt', data, (err) => { if (err) throw err; console.log('The file has been saved!'); }); ``` If `options` is a string, then it specifies the encoding: ```mjs import { writeFile } from 'node:fs'; writeFile('message.txt', 'Hello Node.js', 'utf8', callback); ``` It is unsafe to use `fs.writeFile()` multiple times on the same file without waiting for the callback. For this scenario, [`fs.createWriteStream()`][] is recommended. Similarly to `fs.readFile` - `fs.writeFile` is a convenience method that performs multiple `write` calls internally to write the buffer passed to it. For performance sensitive code consider using [`fs.createWriteStream()`][]. It is possible to use an {AbortSignal} to cancel an `fs.writeFile()`. Cancelation is "best effort", and some amount of data is likely still to be written. ```mjs import { writeFile } from 'node:fs'; import { Buffer } from 'node:buffer'; const controller = new AbortController(); const { signal } = controller; const data = new Uint8Array(Buffer.from('Hello Node.js')); writeFile('message.txt', data, { signal }, (err) => { // When a request is aborted - the callback is called with an AbortError }); // When the request should be aborted controller.abort(); ``` Aborting an ongoing request does not abort individual operating system requests but rather the internal buffering `fs.writeFile` performs. #### Using `fs.writeFile()` with file descriptors When `file` is | https://github.com/nodejs/node/blob/main//doc/api/fs.md | main | nodejs | [
-0.028480863198637962,
0.012077093124389648,
-0.0708724856376648,
-0.01725415140390396,
-0.06949075311422348,
-0.06844735145568848,
-0.0015110507374629378,
0.1242697462439537,
0.057474445551633835,
0.01194633450359106,
-0.027287324890494347,
0.11477995663881302,
0.027594011276960373,
-0.05... | 0.023176 |
When a request is aborted - the callback is called with an AbortError }); // When the request should be aborted controller.abort(); ``` Aborting an ongoing request does not abort individual operating system requests but rather the internal buffering `fs.writeFile` performs. #### Using `fs.writeFile()` with file descriptors When `file` is a file descriptor, the behavior is almost identical to directly calling `fs.write()` like: ```mjs import { write } from 'node:fs'; import { Buffer } from 'node:buffer'; write(fd, Buffer.from(data, options.encoding), callback); ``` The difference from directly calling `fs.write()` is that under some unusual conditions, `fs.write()` might write only part of the buffer and need to be retried to write the remaining data, whereas `fs.writeFile()` retries until the data is entirely written (or an error occurs). The implications of this are a common source of confusion. In the file descriptor case, the file is not replaced! The data is not necessarily written to the beginning of the file, and the file's original data may remain before and/or after the newly written data. For example, if `fs.writeFile()` is called twice in a row, first to write the string `'Hello'`, then to write the string `', World'`, the file would contain `'Hello, World'`, and might contain some of the file's original data (depending on the size of the original file, and the position of the file descriptor). If a file name had been used instead of a descriptor, the file would be guaranteed to contain only `', World'`. ### `fs.writev(fd, buffers[, position], callback)` \* `fd` {integer} \* `buffers` {ArrayBufferView\[]} \* `position` {integer|null} \*\*Default:\*\* `null` \* `callback` {Function} \* `err` {Error} \* `bytesWritten` {integer} \* `buffers` {ArrayBufferView\[]} Write an array of `ArrayBufferView`s to the file specified by `fd` using `writev()`. `position` is the offset from the beginning of the file where this data should be written. If `typeof position !== 'number'`, the data will be written at the current position. The callback will be given three arguments: `err`, `bytesWritten`, and `buffers`. `bytesWritten` is how many bytes were written from `buffers`. If this method is [`util.promisify()`][]ed, it returns a promise for an `Object` with `bytesWritten` and `buffers` properties. It is unsafe to use `fs.writev()` multiple times on the same file without waiting for the callback. For this scenario, use [`fs.createWriteStream()`][]. On Linux, positional writes don't work when the file is opened in append mode. The kernel ignores the position argument and always appends the data to the end of the file. ## Synchronous API The synchronous APIs perform all operations synchronously, blocking the event loop until the operation completes or fails. ### `fs.accessSync(path[, mode])` \* `path` {string|Buffer|URL} \* `mode` {integer} \*\*Default:\*\* `fs.constants.F\_OK` Synchronously tests a user's permissions for the file or directory specified by `path`. The `mode` argument is an optional integer that specifies the accessibility checks to be performed. `mode` should be either the value `fs.constants.F\_OK` or a mask consisting of the bitwise OR of any of `fs.constants.R\_OK`, `fs.constants.W\_OK`, and `fs.constants.X\_OK` (e.g. `fs.constants.W\_OK | fs.constants.R\_OK`). Check [File access constants][] for possible values of `mode`. If any of the accessibility checks fail, an `Error` will be thrown. Otherwise, the method will return `undefined`. ```mjs import { accessSync, constants } from 'node:fs'; try { accessSync('etc/passwd', constants.R\_OK | constants.W\_OK); console.log('can read/write'); } catch (err) { console.error('no access!'); } ``` ### `fs.appendFileSync(path, data[, options])` \* `path` {string|Buffer|URL|number} filename or file descriptor \* `data` {string|Buffer} \* `options` {Object|string} \* `encoding` {string|null} \*\*Default:\*\* `'utf8'` \* `mode` {integer} \*\*Default:\*\* `0o666` \* `flag` {string} See [support of file system `flags`][]. \*\*Default:\*\* `'a'`. \* `flush` {boolean} If `true`, the underlying file descriptor is flushed prior to closing it. \*\*Default:\*\* `false`. Synchronously append data to | https://github.com/nodejs/node/blob/main//doc/api/fs.md | main | nodejs | [
-0.02834681235253811,
0.026391703635454178,
-0.017469439655542374,
0.06185884028673172,
0.057495396584272385,
-0.09928806126117706,
-0.022117601707577705,
0.11084476113319397,
0.09822214394807816,
0.07678651809692383,
-0.027489012107253075,
0.12332818657159805,
-0.0025261705741286278,
-0.0... | 0.12969 |
file descriptor \* `data` {string|Buffer} \* `options` {Object|string} \* `encoding` {string|null} \*\*Default:\*\* `'utf8'` \* `mode` {integer} \*\*Default:\*\* `0o666` \* `flag` {string} See [support of file system `flags`][]. \*\*Default:\*\* `'a'`. \* `flush` {boolean} If `true`, the underlying file descriptor is flushed prior to closing it. \*\*Default:\*\* `false`. Synchronously append data to a file, creating the file if it does not yet exist. `data` can be a string or a {Buffer}. The `mode` option only affects the newly created file. See [`fs.open()`][] for more details. ```mjs import { appendFileSync } from 'node:fs'; try { appendFileSync('message.txt', 'data to append'); console.log('The "data to append" was appended to file!'); } catch (err) { /\* Handle the error \*/ } ``` If `options` is a string, then it specifies the encoding: ```mjs import { appendFileSync } from 'node:fs'; appendFileSync('message.txt', 'data to append', 'utf8'); ``` The `path` may be specified as a numeric file descriptor that has been opened for appending (using `fs.open()` or `fs.openSync()`). The file descriptor will not be closed automatically. ```mjs import { openSync, closeSync, appendFileSync } from 'node:fs'; let fd; try { fd = openSync('message.txt', 'a'); appendFileSync(fd, 'data to append', 'utf8'); } catch (err) { /\* Handle the error \*/ } finally { if (fd !== undefined) closeSync(fd); } ``` ### `fs.chmodSync(path, mode)` \* `path` {string|Buffer|URL} \* `mode` {string|integer} For detailed information, see the documentation of the asynchronous version of this API: [`fs.chmod()`][]. See the POSIX chmod(2) documentation for more detail. ### `fs.chownSync(path, uid, gid)` \* `path` {string|Buffer|URL} \* `uid` {integer} \* `gid` {integer} Synchronously changes owner and group of a file. Returns `undefined`. This is the synchronous version of [`fs.chown()`][]. See the POSIX chown(2) documentation for more detail. ### `fs.closeSync(fd)` \* `fd` {integer} Closes the file descriptor. Returns `undefined`. Calling `fs.closeSync()` on any file descriptor (`fd`) that is currently in use through any other `fs` operation may lead to undefined behavior. See the POSIX close(2) documentation for more detail. ### `fs.copyFileSync(src, dest[, mode])` \* `src` {string|Buffer|URL} source filename to copy \* `dest` {string|Buffer|URL} destination filename of the copy operation \* `mode` {integer} modifiers for copy operation. \*\*Default:\*\* `0`. Synchronously copies `src` to `dest`. By default, `dest` is overwritten if it already exists. Returns `undefined`. Node.js makes no guarantees about the atomicity of the copy operation. If an error occurs after the destination file has been opened for writing, Node.js will attempt to remove the destination. `mode` is an optional integer that specifies the behavior of the copy operation. It is possible to create a mask consisting of the bitwise OR of two or more values (e.g. `fs.constants.COPYFILE\_EXCL | fs.constants.COPYFILE\_FICLONE`). \* `fs.constants.COPYFILE\_EXCL`: The copy operation will fail if `dest` already exists. \* `fs.constants.COPYFILE\_FICLONE`: The copy operation will attempt to create a copy-on-write reflink. If the platform does not support copy-on-write, then a fallback copy mechanism is used. \* `fs.constants.COPYFILE\_FICLONE\_FORCE`: The copy operation will attempt to create a copy-on-write reflink. If the platform does not support copy-on-write, then the operation will fail. ```mjs import { copyFileSync, constants } from 'node:fs'; // destination.txt will be created or overwritten by default. copyFileSync('source.txt', 'destination.txt'); console.log('source.txt was copied to destination.txt'); // By using COPYFILE\_EXCL, the operation will fail if destination.txt exists. copyFileSync('source.txt', 'destination.txt', constants.COPYFILE\_EXCL); ``` ### `fs.cpSync(src, dest[, options])` \* `src` {string|URL} source path to copy. \* `dest` {string|URL} destination path to copy to. \* `options` {Object} \* `dereference` {boolean} dereference symlinks. \*\*Default:\*\* `false`. \* `errorOnExist` {boolean} when `force` is `false`, and the destination exists, throw an error. \*\*Default:\*\* `false`. \* `filter` {Function} Function to filter copied files/directories. Return `true` to copy the item, `false` to ignore it. When ignoring a directory, all of its contents will be | https://github.com/nodejs/node/blob/main//doc/api/fs.md | main | nodejs | [
-0.01909468322992325,
0.05116172134876251,
-0.052629582583904266,
0.061621349304914474,
-0.0009092616965062916,
-0.07400079071521759,
0.01777171716094017,
0.0751853957772255,
0.04570777341723442,
0.035558123141527176,
0.025137633085250854,
0.03794843703508377,
0.006864313967525959,
-0.0122... | 0.08114 |
`dereference` {boolean} dereference symlinks. \*\*Default:\*\* `false`. \* `errorOnExist` {boolean} when `force` is `false`, and the destination exists, throw an error. \*\*Default:\*\* `false`. \* `filter` {Function} Function to filter copied files/directories. Return `true` to copy the item, `false` to ignore it. When ignoring a directory, all of its contents will be skipped as well. \*\*Default:\*\* `undefined` \* `src` {string} source path to copy. \* `dest` {string} destination path to copy to. \* Returns: {boolean} Any non-`Promise` value that is coercible to `boolean`. \* `force` {boolean} overwrite existing file or directory. The copy operation will ignore errors if you set this to false and the destination exists. Use the `errorOnExist` option to change this behavior. \*\*Default:\*\* `true`. \* `mode` {integer} modifiers for copy operation. \*\*Default:\*\* `0`. See `mode` flag of [`fs.copyFileSync()`][]. \* `preserveTimestamps` {boolean} When `true` timestamps from `src` will be preserved. \*\*Default:\*\* `false`. \* `recursive` {boolean} copy directories recursively \*\*Default:\*\* `false` \* `verbatimSymlinks` {boolean} When `true`, path resolution for symlinks will be skipped. \*\*Default:\*\* `false` Synchronously copies the entire directory structure from `src` to `dest`, including subdirectories and files. When copying a directory to another directory, globs are not supported and behavior is similar to `cp dir1/ dir2/`. ### `fs.existsSync(path)` \* `path` {string|Buffer|URL} \* Returns: {boolean} Returns `true` if the path exists, `false` otherwise. For detailed information, see the documentation of the asynchronous version of this API: [`fs.exists()`][]. `fs.exists()` is deprecated, but `fs.existsSync()` is not. The `callback` parameter to `fs.exists()` accepts parameters that are inconsistent with other Node.js callbacks. `fs.existsSync()` does not use a callback. ```mjs import { existsSync } from 'node:fs'; if (existsSync('/etc/passwd')) console.log('The path exists.'); ``` ### `fs.fchmodSync(fd, mode)` \* `fd` {integer} \* `mode` {string|integer} Sets the permissions on the file. Returns `undefined`. See the POSIX fchmod(2) documentation for more detail. ### `fs.fchownSync(fd, uid, gid)` \* `fd` {integer} \* `uid` {integer} The file's new owner's user id. \* `gid` {integer} The file's new group's group id. Sets the owner of the file. Returns `undefined`. See the POSIX fchown(2) documentation for more detail. ### `fs.fdatasyncSync(fd)` \* `fd` {integer} Forces all currently queued I/O operations associated with the file to the operating system's synchronized I/O completion state. Refer to the POSIX fdatasync(2) documentation for details. Returns `undefined`. ### `fs.fstatSync(fd[, options])` \* `fd` {integer} \* `options` {Object} \* `bigint` {boolean} Whether the numeric values in the returned {fs.Stats} object should be `bigint`. \*\*Default:\*\* `false`. \* Returns: {fs.Stats} Retrieves the {fs.Stats} for the file descriptor. See the POSIX fstat(2) documentation for more detail. ### `fs.fsyncSync(fd)` \* `fd` {integer} Request that all data for the open file descriptor is flushed to the storage device. The specific implementation is operating system and device specific. Refer to the POSIX fsync(2) documentation for more detail. Returns `undefined`. ### `fs.ftruncateSync(fd[, len])` \* `fd` {integer} \* `len` {integer} \*\*Default:\*\* `0` Truncates the file descriptor. Returns `undefined`. For detailed information, see the documentation of the asynchronous version of this API: [`fs.ftruncate()`][]. ### `fs.futimesSync(fd, atime, mtime)` \* `fd` {integer} \* `atime` {number|string|Date} \* `mtime` {number|string|Date} Synchronous version of [`fs.futimes()`][]. Returns `undefined`. ### `fs.globSync(pattern[, options])` \* `pattern` {string|string\[]} \* `options` {Object} \* `cwd` {string|URL} current working directory. \*\*Default:\*\* `process.cwd()` \* `exclude` {Function|string\[]} Function to filter out files/directories or a list of glob patterns to be excluded. If a function is provided, return `true` to exclude the item, `false` to include it. \*\*Default:\*\* `undefined`. \* `withFileTypes` {boolean} `true` if the glob should return paths as Dirents, `false` otherwise. \*\*Default:\*\* `false`. \* Returns: {string\[]} paths of files that match the pattern. ```mjs import { globSync } from 'node:fs'; console.log(globSync('\*\*/\*.js')); ``` ```cjs const { globSync } = require('node:fs'); console.log(globSync('\*\*/\*.js')); ``` ### `fs.lchmodSync(path, mode)` > Stability: | https://github.com/nodejs/node/blob/main//doc/api/fs.md | main | nodejs | [
-0.06672873347997665,
-0.013722418807446957,
0.04252097010612488,
0.05956094712018967,
0.065125972032547,
-0.055739667266607285,
0.03406226262450218,
-0.018393240869045258,
0.03557002171874046,
0.024388419464230537,
0.0784500390291214,
-0.02219424396753311,
0.013085491955280304,
0.01898821... | 0.05461 |
`undefined`. \* `withFileTypes` {boolean} `true` if the glob should return paths as Dirents, `false` otherwise. \*\*Default:\*\* `false`. \* Returns: {string\[]} paths of files that match the pattern. ```mjs import { globSync } from 'node:fs'; console.log(globSync('\*\*/\*.js')); ``` ```cjs const { globSync } = require('node:fs'); console.log(globSync('\*\*/\*.js')); ``` ### `fs.lchmodSync(path, mode)` > Stability: 0 - Deprecated \* `path` {string|Buffer|URL} \* `mode` {integer} Changes the permissions on a symbolic link. Returns `undefined`. This method is only implemented on macOS. See the POSIX lchmod(2) documentation for more detail. ### `fs.lchownSync(path, uid, gid)` \* `path` {string|Buffer|URL} \* `uid` {integer} The file's new owner's user id. \* `gid` {integer} The file's new group's group id. Set the owner for the path. Returns `undefined`. See the POSIX lchown(2) documentation for more details. ### `fs.lutimesSync(path, atime, mtime)` \* `path` {string|Buffer|URL} \* `atime` {number|string|Date} \* `mtime` {number|string|Date} Change the file system timestamps of the symbolic link referenced by `path`. Returns `undefined`, or throws an exception when parameters are incorrect or the operation fails. This is the synchronous version of [`fs.lutimes()`][]. ### `fs.linkSync(existingPath, newPath)` \* `existingPath` {string|Buffer|URL} \* `newPath` {string|Buffer|URL} Creates a new link from the `existingPath` to the `newPath`. See the POSIX link(2) documentation for more detail. Returns `undefined`. ### `fs.lstatSync(path[, options])` \* `path` {string|Buffer|URL} \* `options` {Object} \* `bigint` {boolean} Whether the numeric values in the returned {fs.Stats} object should be `bigint`. \*\*Default:\*\* `false`. \* `throwIfNoEntry` {boolean} Whether an exception will be thrown if no file system entry exists, rather than returning `undefined`. \*\*Default:\*\* `true`. \* Returns: {fs.Stats} Retrieves the {fs.Stats} for the symbolic link referred to by `path`. See the POSIX lstat(2) documentation for more details. ### `fs.mkdirSync(path[, options])` \* `path` {string|Buffer|URL} \* `options` {Object|integer} \* `recursive` {boolean} \*\*Default:\*\* `false` \* `mode` {string|integer} Not supported on Windows. \*\*Default:\*\* `0o777`. \* Returns: {string|undefined} Synchronously creates a directory. Returns `undefined`, or if `recursive` is `true`, the first directory path created. This is the synchronous version of [`fs.mkdir()`][]. See the POSIX mkdir(2) documentation for more details. ### `fs.mkdtempSync(prefix[, options])` \* `prefix` {string|Buffer|URL} \* `options` {string|Object} \* `encoding` {string} \*\*Default:\*\* `'utf8'` \* Returns: {string} Returns the created directory path. For detailed information, see the documentation of the asynchronous version of this API: [`fs.mkdtemp()`][]. The optional `options` argument can be a string specifying an encoding, or an object with an `encoding` property specifying the character encoding to use. ### `fs.mkdtempDisposableSync(prefix[, options])` \* `prefix` {string|Buffer|URL} \* `options` {string|Object} \* `encoding` {string} \*\*Default:\*\* `'utf8'` \* Returns: {Object} A disposable object: \* `path` {string} The path of the created directory. \* `remove` {Function} A function which removes the created directory. \* `[Symbol.dispose]` {Function} The same as `remove`. Returns a disposable object whose `path` property holds the created directory path. When the object is disposed, the directory and its contents will be removed if it still exists. If the directory cannot be deleted, disposal will throw an error. The object has a `remove()` method which will perform the same task. For detailed information, see the documentation of [`fs.mkdtemp()`][]. There is no callback-based version of this API because it is designed for use with the `using` syntax. The optional `options` argument can be a string specifying an encoding, or an object with an `encoding` property specifying the character encoding to use. ### `fs.opendirSync(path[, options])` \* `path` {string|Buffer|URL} \* `options` {Object} \* `encoding` {string|null} \*\*Default:\*\* `'utf8'` \* `bufferSize` {number} Number of directory entries that are buffered internally when reading from the directory. Higher values lead to better performance but higher memory usage. \*\*Default:\*\* `32` \* `recursive` {boolean} \*\*Default:\*\* `false` \* Returns: {fs.Dir} Synchronously open a directory. See opendir(3). Creates an {fs.Dir}, which contains all further functions for reading from | https://github.com/nodejs/node/blob/main//doc/api/fs.md | main | nodejs | [
-0.057581521570682526,
0.011845345608890057,
-0.024455083534121513,
0.008197984658181667,
0.06461324542760849,
-0.04385614022612572,
0.015382859855890274,
0.05018960312008858,
-0.007059434428811073,
-0.03272392973303795,
0.0006257392233237624,
0.055011067539453506,
-0.0055138240568339825,
... | 0.047642 |
Number of directory entries that are buffered internally when reading from the directory. Higher values lead to better performance but higher memory usage. \*\*Default:\*\* `32` \* `recursive` {boolean} \*\*Default:\*\* `false` \* Returns: {fs.Dir} Synchronously open a directory. See opendir(3). Creates an {fs.Dir}, which contains all further functions for reading from and cleaning up the directory. The `encoding` option sets the encoding for the `path` while opening the directory and subsequent read operations. ### `fs.openSync(path[, flags[, mode]])` \* `path` {string|Buffer|URL} \* `flags` {string|number} \*\*Default:\*\* `'r'`. See [support of file system `flags`][]. \* `mode` {string|integer} \*\*Default:\*\* `0o666` \* Returns: {number} Returns an integer representing the file descriptor. For detailed information, see the documentation of the asynchronous version of this API: [`fs.open()`][]. ### `fs.readdirSync(path[, options])` \* `path` {string|Buffer|URL} \* `options` {string|Object} \* `encoding` {string} \*\*Default:\*\* `'utf8'` \* `withFileTypes` {boolean} \*\*Default:\*\* `false` \* `recursive` {boolean} If `true`, reads the contents of a directory recursively. In recursive mode, it will list all files, sub files, and directories. \*\*Default:\*\* `false`. \* Returns: {string\[]|Buffer\[]|fs.Dirent\[]} Reads the contents of the directory. See the POSIX readdir(3) documentation for more details. The optional `options` argument can be a string specifying an encoding, or an object with an `encoding` property specifying the character encoding to use for the filenames returned. If the `encoding` is set to `'buffer'`, the filenames returned will be passed as {Buffer} objects. If `options.withFileTypes` is set to `true`, the result will contain {fs.Dirent} objects. ### `fs.readFileSync(path[, options])` \* `path` {string|Buffer|URL|integer} filename or file descriptor \* `options` {Object|string} \* `encoding` {string|null} \*\*Default:\*\* `null` \* `flag` {string} See [support of file system `flags`][]. \*\*Default:\*\* `'r'`. \* Returns: {string|Buffer} Returns the contents of the `path`. For detailed information, see the documentation of the asynchronous version of this API: [`fs.readFile()`][]. If the `encoding` option is specified then this function returns a string. Otherwise it returns a buffer. Similar to [`fs.readFile()`][], when the path is a directory, the behavior of `fs.readFileSync()` is platform-specific. ```mjs import { readFileSync } from 'node:fs'; // macOS, Linux, and Windows readFileSync(''); // => [Error: EISDIR: illegal operation on a directory, read ] // FreeBSD readFileSync(''); // => ``` ### `fs.readlinkSync(path[, options])` \* `path` {string|Buffer|URL} \* `options` {string|Object} \* `encoding` {string} \*\*Default:\*\* `'utf8'` \* Returns: {string|Buffer} Returns the symbolic link's string value. See the POSIX readlink(2) documentation for more details. The optional `options` argument can be a string specifying an encoding, or an object with an `encoding` property specifying the character encoding to use for the link path returned. If the `encoding` is set to `'buffer'`, the link path returned will be passed as a {Buffer} object. ### `fs.readSync(fd, buffer, offset, length[, position])` \* `fd` {integer} \* `buffer` {Buffer|TypedArray|DataView} \* `offset` {integer} \* `length` {integer} \* `position` {integer|bigint|null} \*\*Default:\*\* `null` \* Returns: {number} Returns the number of `bytesRead`. For detailed information, see the documentation of the asynchronous version of this API: [`fs.read()`][]. ### `fs.readSync(fd, buffer[, options])` \* `fd` {integer} \* `buffer` {Buffer|TypedArray|DataView} \* `options` {Object} \* `offset` {integer} \*\*Default:\*\* `0` \* `length` {integer} \*\*Default:\*\* `buffer.byteLength - offset` \* `position` {integer|bigint|null} \*\*Default:\*\* `null` \* Returns: {number} Returns the number of `bytesRead`. Similar to the above `fs.readSync` function, this version takes an optional `options` object. If no `options` object is specified, it will default with the above values. For detailed information, see the documentation of the asynchronous version of this API: [`fs.read()`][]. ### `fs.readvSync(fd, buffers[, position])` \* `fd` {integer} \* `buffers` {ArrayBufferView\[]} \* `position` {integer|null} \*\*Default:\*\* `null` \* Returns: {number} The number of bytes read. For detailed information, see the documentation of the asynchronous version of this API: [`fs.readv()`][]. ### `fs.realpathSync(path[, options])` \* `path` {string|Buffer|URL} \* `options` {string|Object} \* `encoding` | https://github.com/nodejs/node/blob/main//doc/api/fs.md | main | nodejs | [
0.0030757721979171038,
0.009016918949782848,
-0.11986096948385239,
0.04559972882270813,
0.037889208644628525,
-0.0770227238535881,
-0.015785546973347664,
0.09036460518836975,
0.09073427319526672,
-0.037004683166742325,
-0.019966118037700653,
0.09761933237314224,
-0.027846792712807655,
0.01... | 0.076393 |
API: [`fs.read()`][]. ### `fs.readvSync(fd, buffers[, position])` \* `fd` {integer} \* `buffers` {ArrayBufferView\[]} \* `position` {integer|null} \*\*Default:\*\* `null` \* Returns: {number} The number of bytes read. For detailed information, see the documentation of the asynchronous version of this API: [`fs.readv()`][]. ### `fs.realpathSync(path[, options])` \* `path` {string|Buffer|URL} \* `options` {string|Object} \* `encoding` {string} \*\*Default:\*\* `'utf8'` \* Returns: {string|Buffer} Returns the resolved pathname. For detailed information, see the documentation of the asynchronous version of this API: [`fs.realpath()`][]. ### `fs.realpathSync.native(path[, options])` \* `path` {string|Buffer|URL} \* `options` {string|Object} \* `encoding` {string} \*\*Default:\*\* `'utf8'` \* Returns: {string|Buffer} Synchronous realpath(3). Only paths that can be converted to UTF8 strings are supported. The optional `options` argument can be a string specifying an encoding, or an object with an `encoding` property specifying the character encoding to use for the path returned. If the `encoding` is set to `'buffer'`, the path returned will be passed as a {Buffer} object. On Linux, when Node.js is linked against musl libc, the procfs file system must be mounted on `/proc` in order for this function to work. Glibc does not have this restriction. ### `fs.renameSync(oldPath, newPath)` \* `oldPath` {string|Buffer|URL} \* `newPath` {string|Buffer|URL} Renames the file from `oldPath` to `newPath`. Returns `undefined`. See the POSIX rename(2) documentation for more details. ### `fs.rmdirSync(path[, options])` \* `path` {string|Buffer|URL} \* `options` {Object} There are currently no options exposed. There used to be options for `recursive`, `maxBusyTries`, and `emfileWait` but they were deprecated and removed. The `options` argument is still accepted for backwards compatibility but it is not used. Synchronous rmdir(2). Returns `undefined`. Using `fs.rmdirSync()` on a file (not a directory) results in an `ENOENT` error on Windows and an `ENOTDIR` error on POSIX. To get a behavior similar to the `rm -rf` Unix command, use [`fs.rmSync()`][] with options `{ recursive: true, force: true }`. ### `fs.rmSync(path[, options])` \* `path` {string|Buffer|URL} \* `options` {Object} \* `force` {boolean} When `true`, exceptions will be ignored if `path` does not exist. \*\*Default:\*\* `false`. \* `maxRetries` {integer} If an `EBUSY`, `EMFILE`, `ENFILE`, `ENOTEMPTY`, or `EPERM` error is encountered, Node.js will retry the operation with a linear backoff wait of `retryDelay` milliseconds longer on each try. This option represents the number of retries. This option is ignored if the `recursive` option is not `true`. \*\*Default:\*\* `0`. \* `recursive` {boolean} If `true`, perform a recursive directory removal. In recursive mode operations are retried on failure. \*\*Default:\*\* `false`. \* `retryDelay` {integer} The amount of time in milliseconds to wait between retries. This option is ignored if the `recursive` option is not `true`. \*\*Default:\*\* `100`. Synchronously removes files and directories (modeled on the standard POSIX `rm` utility). Returns `undefined`. ### `fs.statSync(path[, options])` \* `path` {string|Buffer|URL} \* `options` {Object} \* `bigint` {boolean} Whether the numeric values in the returned {fs.Stats} object should be `bigint`. \*\*Default:\*\* `false`. \* `throwIfNoEntry` {boolean} Whether an exception will be thrown if no file system entry exists, rather than returning `undefined`. \*\*Default:\*\* `true`. \* Returns: {fs.Stats} Retrieves the {fs.Stats} for the path. ### `fs.statfsSync(path[, options])` \* `path` {string|Buffer|URL} \* `options` {Object} \* `bigint` {boolean} Whether the numeric values in the returned {fs.StatFs} object should be `bigint`. \*\*Default:\*\* `false`. \* Returns: {fs.StatFs} Synchronous statfs(2). Returns information about the mounted file system which contains `path`. In case of an error, the `err.code` will be one of [Common System Errors][]. ### `fs.symlinkSync(target, path[, type])` \* `target` {string|Buffer|URL} \* `path` {string|Buffer|URL} \* `type` {string|null} \*\*Default:\*\* `null` \* Returns: `undefined`. For detailed information, see the documentation of the asynchronous version of this API: [`fs.symlink()`][]. ### `fs.truncateSync(path[, len])` \* `path` {string|Buffer|URL} \* `len` {integer} \*\*Default:\*\* `0` Truncates the file. Returns `undefined`. A file descriptor can also be passed as | https://github.com/nodejs/node/blob/main//doc/api/fs.md | main | nodejs | [
-0.011018987745046616,
-0.017163636162877083,
-0.1735934615135193,
0.02635389380156994,
-0.03377887234091759,
-0.06979923695325851,
-0.011803139001131058,
0.07766846567392349,
0.04257912188768387,
-0.05517297610640526,
-0.0713832899928093,
0.03356640040874481,
-0.05165763944387436,
-0.0089... | 0.081773 |
{string|Buffer|URL} \* `path` {string|Buffer|URL} \* `type` {string|null} \*\*Default:\*\* `null` \* Returns: `undefined`. For detailed information, see the documentation of the asynchronous version of this API: [`fs.symlink()`][]. ### `fs.truncateSync(path[, len])` \* `path` {string|Buffer|URL} \* `len` {integer} \*\*Default:\*\* `0` Truncates the file. Returns `undefined`. A file descriptor can also be passed as the first argument. In this case, `fs.ftruncateSync()` is called. Passing a file descriptor is deprecated and may result in an error being thrown in the future. ### `fs.unlinkSync(path)` \* `path` {string|Buffer|URL} Synchronous unlink(2). Returns `undefined`. ### `fs.utimesSync(path, atime, mtime)` \* `path` {string|Buffer|URL} \* `atime` {number|string|Date} \* `mtime` {number|string|Date} \* Returns: `undefined`. For detailed information, see the documentation of the asynchronous version of this API: [`fs.utimes()`][]. ### `fs.writeFileSync(file, data[, options])` \* `file` {string|Buffer|URL|integer} filename or file descriptor \* `data` {string|Buffer|TypedArray|DataView} \* `options` {Object|string} \* `encoding` {string|null} \*\*Default:\*\* `'utf8'` \* `mode` {integer} \*\*Default:\*\* `0o666` \* `flag` {string} See [support of file system `flags`][]. \*\*Default:\*\* `'w'`. \* `flush` {boolean} If all data is successfully written to the file, and `flush` is `true`, `fs.fsyncSync()` is used to flush the data. \* Returns: `undefined`. The `mode` option only affects the newly created file. See [`fs.open()`][] for more details. For detailed information, see the documentation of the asynchronous version of this API: [`fs.writeFile()`][]. ### `fs.writeSync(fd, buffer, offset[, length[, position]])` \* `fd` {integer} \* `buffer` {Buffer|TypedArray|DataView} \* `offset` {integer} \*\*Default:\*\* `0` \* `length` {integer} \*\*Default:\*\* `buffer.byteLength - offset` \* `position` {integer|null} \*\*Default:\*\* `null` \* Returns: {number} The number of bytes written. For detailed information, see the documentation of the asynchronous version of this API: [`fs.write(fd, buffer...)`][]. ### `fs.writeSync(fd, buffer[, options])` \* `fd` {integer} \* `buffer` {Buffer|TypedArray|DataView} \* `options` {Object} \* `offset` {integer} \*\*Default:\*\* `0` \* `length` {integer} \*\*Default:\*\* `buffer.byteLength - offset` \* `position` {integer|null} \*\*Default:\*\* `null` \* Returns: {number} The number of bytes written. For detailed information, see the documentation of the asynchronous version of this API: [`fs.write(fd, buffer...)`][]. ### `fs.writeSync(fd, string[, position[, encoding]])` \* `fd` {integer} \* `string` {string} \* `position` {integer|null} \*\*Default:\*\* `null` \* `encoding` {string} \*\*Default:\*\* `'utf8'` \* Returns: {number} The number of bytes written. For detailed information, see the documentation of the asynchronous version of this API: [`fs.write(fd, string...)`][]. ### `fs.writevSync(fd, buffers[, position])` \* `fd` {integer} \* `buffers` {ArrayBufferView\[]} \* `position` {integer|null} \*\*Default:\*\* `null` \* Returns: {number} The number of bytes written. For detailed information, see the documentation of the asynchronous version of this API: [`fs.writev()`][]. ## Common Objects The common objects are shared by all of the file system API variants (promise, callback, and synchronous). ### Class: `fs.Dir` A class representing a directory stream. Created by [`fs.opendir()`][], [`fs.opendirSync()`][], or [`fsPromises.opendir()`][]. ```mjs import { opendir } from 'node:fs/promises'; try { const dir = await opendir('./'); for await (const dirent of dir) console.log(dirent.name); } catch (err) { console.error(err); } ``` When using the async iterator, the {fs.Dir} object will be automatically closed after the iterator exits. #### `dir.close()` \* Returns: {Promise} Asynchronously close the directory's underlying resource handle. Subsequent reads will result in errors. A promise is returned that will be fulfilled after the resource has been closed. #### `dir.close(callback)` \* `callback` {Function} \* `err` {Error} Asynchronously close the directory's underlying resource handle. Subsequent reads will result in errors. The `callback` will be called after the resource handle has been closed. #### `dir.closeSync()` Synchronously close the directory's underlying resource handle. Subsequent reads will result in errors. #### `dir.path` \* Type: {string} The read-only path of this directory as was provided to [`fs.opendir()`][], [`fs.opendirSync()`][], or [`fsPromises.opendir()`][]. #### `dir.read()` \* Returns: {Promise} Fulfills with a {fs.Dirent|null} Asynchronously read the next directory entry via readdir(3) as an {fs.Dirent}. A promise is returned that will be fulfilled with | https://github.com/nodejs/node/blob/main//doc/api/fs.md | main | nodejs | [
-0.04053020477294922,
0.02652408927679062,
-0.07221967726945877,
0.09039293974637985,
0.008609640412032604,
-0.08187245577573776,
-0.030882377177476883,
0.10901578515768051,
0.033116552978754044,
-0.01860930770635605,
0.0017763461219146848,
0.10883655399084091,
-0.04805084690451622,
-0.000... | 0.107861 |
in errors. #### `dir.path` \* Type: {string} The read-only path of this directory as was provided to [`fs.opendir()`][], [`fs.opendirSync()`][], or [`fsPromises.opendir()`][]. #### `dir.read()` \* Returns: {Promise} Fulfills with a {fs.Dirent|null} Asynchronously read the next directory entry via readdir(3) as an {fs.Dirent}. A promise is returned that will be fulfilled with an {fs.Dirent}, or `null` if there are no more directory entries to read. Directory entries returned by this function are in no particular order as provided by the operating system's underlying directory mechanisms. Entries added or removed while iterating over the directory might not be included in the iteration results. #### `dir.read(callback)` \* `callback` {Function} \* `err` {Error} \* `dirent` {fs.Dirent|null} Asynchronously read the next directory entry via readdir(3) as an {fs.Dirent}. After the read is completed, the `callback` will be called with an {fs.Dirent}, or `null` if there are no more directory entries to read. Directory entries returned by this function are in no particular order as provided by the operating system's underlying directory mechanisms. Entries added or removed while iterating over the directory might not be included in the iteration results. #### `dir.readSync()` \* Returns: {fs.Dirent|null} Synchronously read the next directory entry as an {fs.Dirent}. See the POSIX readdir(3) documentation for more detail. If there are no more directory entries to read, `null` will be returned. Directory entries returned by this function are in no particular order as provided by the operating system's underlying directory mechanisms. Entries added or removed while iterating over the directory might not be included in the iteration results. #### `dir[Symbol.asyncIterator]()` \* Returns: {AsyncIterator} An AsyncIterator of {fs.Dirent} Asynchronously iterates over the directory until all entries have been read. Refer to the POSIX readdir(3) documentation for more detail. Entries returned by the async iterator are always an {fs.Dirent}. The `null` case from `dir.read()` is handled internally. See {fs.Dir} for an example. Directory entries returned by this iterator are in no particular order as provided by the operating system's underlying directory mechanisms. Entries added or removed while iterating over the directory might not be included in the iteration results. #### `dir[Symbol.asyncDispose]()` Calls `dir.close()` if the directory handle is open, and returns a promise that fulfills when disposal is complete. #### `dir[Symbol.dispose]()` Calls `dir.closeSync()` if the directory handle is open, and returns `undefined`. ### Class: `fs.Dirent` A representation of a directory entry, which can be a file or a subdirectory within the directory, as returned by reading from an {fs.Dir}. The directory entry is a combination of the file name and file type pairs. Additionally, when [`fs.readdir()`][] or [`fs.readdirSync()`][] is called with the `withFileTypes` option set to `true`, the resulting array is filled with {fs.Dirent} objects, rather than strings or {Buffer}s. #### `dirent.isBlockDevice()` \* Returns: {boolean} Returns `true` if the {fs.Dirent} object describes a block device. #### `dirent.isCharacterDevice()` \* Returns: {boolean} Returns `true` if the {fs.Dirent} object describes a character device. #### `dirent.isDirectory()` \* Returns: {boolean} Returns `true` if the {fs.Dirent} object describes a file system directory. #### `dirent.isFIFO()` \* Returns: {boolean} Returns `true` if the {fs.Dirent} object describes a first-in-first-out (FIFO) pipe. #### `dirent.isFile()` \* Returns: {boolean} Returns `true` if the {fs.Dirent} object describes a regular file. #### `dirent.isSocket()` \* Returns: {boolean} Returns `true` if the {fs.Dirent} object describes a socket. #### `dirent.isSymbolicLink()` \* Returns: {boolean} Returns `true` if the {fs.Dirent} object describes a symbolic link. #### `dirent.name` \* Type: {string|Buffer} The file name that this {fs.Dirent} object refers to. The type of this value is determined by the `options.encoding` passed to [`fs.readdir()`][] or [`fs.readdirSync()`][]. #### `dirent.parentPath` \* Type: {string} The path to the parent directory of the file this {fs.Dirent} object refers to. ### | https://github.com/nodejs/node/blob/main//doc/api/fs.md | main | nodejs | [
-0.11628064513206482,
0.0072518824599683285,
-0.05224931612610817,
0.09729799628257751,
0.08892377465963364,
-0.10388953238725662,
-0.02793726697564125,
0.12407175451517105,
0.09981519728899002,
-0.060312382876873016,
0.043518759310245514,
0.09926681965589523,
-0.016078272834420204,
0.0029... | 0.054286 |
link. #### `dirent.name` \* Type: {string|Buffer} The file name that this {fs.Dirent} object refers to. The type of this value is determined by the `options.encoding` passed to [`fs.readdir()`][] or [`fs.readdirSync()`][]. #### `dirent.parentPath` \* Type: {string} The path to the parent directory of the file this {fs.Dirent} object refers to. ### Class: `fs.FSWatcher` \* Extends {EventEmitter} A successful call to [`fs.watch()`][] method will return a new {fs.FSWatcher} object. All {fs.FSWatcher} objects emit a `'change'` event whenever a specific watched file is modified. #### Event: `'change'` \* `eventType` {string} The type of change event that has occurred \* `filename` {string|Buffer} The filename that changed (if relevant/available) Emitted when something changes in a watched directory or file. See more details in [`fs.watch()`][]. The `filename` argument may not be provided depending on operating system support. If `filename` is provided, it will be provided as a {Buffer} if `fs.watch()` is called with its `encoding` option set to `'buffer'`, otherwise `filename` will be a UTF-8 string. ```mjs import { watch } from 'node:fs'; // Example when handled through fs.watch() listener watch('./tmp', { encoding: 'buffer' }, (eventType, filename) => { if (filename) { console.log(filename); // Prints: } }); ``` #### Event: `'close'` Emitted when the watcher stops watching for changes. The closed {fs.FSWatcher} object is no longer usable in the event handler. #### Event: `'error'` \* `error` {Error} Emitted when an error occurs while watching the file. The errored {fs.FSWatcher} object is no longer usable in the event handler. #### `watcher.close()` Stop watching for changes on the given {fs.FSWatcher}. Once stopped, the {fs.FSWatcher} object is no longer usable. #### `watcher.ref()` \* Returns: {fs.FSWatcher} When called, requests that the Node.js event loop \_not\_ exit so long as the {fs.FSWatcher} is active. Calling `watcher.ref()` multiple times will have no effect. By default, all {fs.FSWatcher} objects are "ref'ed", making it normally unnecessary to call `watcher.ref()` unless `watcher.unref()` had been called previously. #### `watcher.unref()` \* Returns: {fs.FSWatcher} When called, the active {fs.FSWatcher} object will not require the Node.js event loop to remain active. If there is no other activity keeping the event loop running, the process may exit before the {fs.FSWatcher} object's callback is invoked. Calling `watcher.unref()` multiple times will have no effect. ### Class: `fs.StatWatcher` \* Extends {EventEmitter} A successful call to `fs.watchFile()` method will return a new {fs.StatWatcher} object. #### `watcher.ref()` \* Returns: {fs.StatWatcher} When called, requests that the Node.js event loop \_not\_ exit so long as the {fs.StatWatcher} is active. Calling `watcher.ref()` multiple times will have no effect. By default, all {fs.StatWatcher} objects are "ref'ed", making it normally unnecessary to call `watcher.ref()` unless `watcher.unref()` had been called previously. #### `watcher.unref()` \* Returns: {fs.StatWatcher} When called, the active {fs.StatWatcher} object will not require the Node.js event loop to remain active. If there is no other activity keeping the event loop running, the process may exit before the {fs.StatWatcher} object's callback is invoked. Calling `watcher.unref()` multiple times will have no effect. ### Class: `fs.ReadStream` \* Extends: {stream.Readable} Instances of {fs.ReadStream} are created and returned using the [`fs.createReadStream()`][] function. #### Event: `'close'` Emitted when the {fs.ReadStream}'s underlying file descriptor has been closed. #### Event: `'open'` \* `fd` {integer} Integer file descriptor used by the {fs.ReadStream}. Emitted when the {fs.ReadStream}'s file descriptor has been opened. #### Event: `'ready'` Emitted when the {fs.ReadStream} is ready to be used. Fires immediately after `'open'`. #### `readStream.bytesRead` \* Type: {number} The number of bytes that have been read so far. #### `readStream.path` \* Type: {string|Buffer} The path to the file the stream is reading from as specified in the first argument to `fs.createReadStream()`. If `path` is passed as a string, then `readStream.path` will be a string. | https://github.com/nodejs/node/blob/main//doc/api/fs.md | main | nodejs | [
-0.06444602459669113,
0.033875543624162674,
-0.0868578553199768,
0.03713066503405571,
0.06197405233979225,
-0.045359183102846146,
0.056223876774311066,
0.18013626337051392,
0.07456913590431213,
0.01391853392124176,
-0.042636025696992874,
0.001318282214924693,
-0.07297329604625702,
0.050660... | 0.173438 |
`readStream.bytesRead` \* Type: {number} The number of bytes that have been read so far. #### `readStream.path` \* Type: {string|Buffer} The path to the file the stream is reading from as specified in the first argument to `fs.createReadStream()`. If `path` is passed as a string, then `readStream.path` will be a string. If `path` is passed as a {Buffer}, then `readStream.path` will be a {Buffer}. If `fd` is specified, then `readStream.path` will be `undefined`. #### `readStream.pending` \* Type: {boolean} This property is `true` if the underlying file has not been opened yet, i.e. before the `'ready'` event is emitted. ### Class: `fs.Stats` A {fs.Stats} object provides information about a file. Objects returned from [`fs.stat()`][], [`fs.lstat()`][], [`fs.fstat()`][], and their synchronous counterparts are of this type. If `bigint` in the `options` passed to those methods is true, the numeric values will be `bigint` instead of `number`, and the object will contain additional nanosecond-precision properties suffixed with `Ns`. `Stat` objects are not to be created directly using the `new` keyword. ```console Stats { dev: 2114, ino: 48064969, mode: 33188, nlink: 1, uid: 85, gid: 100, rdev: 0, size: 527, blksize: 4096, blocks: 8, atimeMs: 1318289051000.1, mtimeMs: 1318289051000.1, ctimeMs: 1318289051000.1, birthtimeMs: 1318289051000.1, atime: Mon, 10 Oct 2011 23:24:11 GMT, mtime: Mon, 10 Oct 2011 23:24:11 GMT, ctime: Mon, 10 Oct 2011 23:24:11 GMT, birthtime: Mon, 10 Oct 2011 23:24:11 GMT } ``` `bigint` version: ```console BigIntStats { dev: 2114n, ino: 48064969n, mode: 33188n, nlink: 1n, uid: 85n, gid: 100n, rdev: 0n, size: 527n, blksize: 4096n, blocks: 8n, atimeMs: 1318289051000n, mtimeMs: 1318289051000n, ctimeMs: 1318289051000n, birthtimeMs: 1318289051000n, atimeNs: 1318289051000000000n, mtimeNs: 1318289051000000000n, ctimeNs: 1318289051000000000n, birthtimeNs: 1318289051000000000n, atime: Mon, 10 Oct 2011 23:24:11 GMT, mtime: Mon, 10 Oct 2011 23:24:11 GMT, ctime: Mon, 10 Oct 2011 23:24:11 GMT, birthtime: Mon, 10 Oct 2011 23:24:11 GMT } ``` #### `stats.isBlockDevice()` \* Returns: {boolean} Returns `true` if the {fs.Stats} object describes a block device. #### `stats.isCharacterDevice()` \* Returns: {boolean} Returns `true` if the {fs.Stats} object describes a character device. #### `stats.isDirectory()` \* Returns: {boolean} Returns `true` if the {fs.Stats} object describes a file system directory. If the {fs.Stats} object was obtained from calling [`fs.lstat()`][] on a symbolic link which resolves to a directory, this method will return `false`. This is because [`fs.lstat()`][] returns information about a symbolic link itself and not the path it resolves to. #### `stats.isFIFO()` \* Returns: {boolean} Returns `true` if the {fs.Stats} object describes a first-in-first-out (FIFO) pipe. #### `stats.isFile()` \* Returns: {boolean} Returns `true` if the {fs.Stats} object describes a regular file. #### `stats.isSocket()` \* Returns: {boolean} Returns `true` if the {fs.Stats} object describes a socket. #### `stats.isSymbolicLink()` \* Returns: {boolean} Returns `true` if the {fs.Stats} object describes a symbolic link. This method is only valid when using [`fs.lstat()`][]. #### `stats.dev` \* Type: {number|bigint} The numeric identifier of the device containing the file. #### `stats.ino` \* Type: {number|bigint} The file system specific "Inode" number for the file. #### `stats.mode` \* Type: {number|bigint} A bit-field describing the file type and mode. #### `stats.nlink` \* Type: {number|bigint} The number of hard-links that exist for the file. #### `stats.uid` \* Type: {number|bigint} The numeric user identifier of the user that owns the file (POSIX). #### `stats.gid` \* Type: {number|bigint} The numeric group identifier of the group that owns the file (POSIX). #### `stats.rdev` \* Type: {number|bigint} A numeric device identifier if the file represents a device. #### `stats.size` \* Type: {number|bigint} The size of the file in bytes. If the underlying file system does not support getting the size of the file, this will be `0`. #### `stats.blksize` \* Type: {number|bigint} The file system block size for i/o operations. #### | https://github.com/nodejs/node/blob/main//doc/api/fs.md | main | nodejs | [
-0.04253866523504257,
-0.009950928390026093,
-0.098615862429142,
0.06113665550947189,
-0.002564248163253069,
-0.06908498704433441,
0.022275343537330627,
0.1314704418182373,
0.07308485358953476,
0.01856238953769207,
-0.05801425501704216,
0.10886283963918686,
-0.042170554399490356,
0.0310521... | 0.128142 |
if the file represents a device. #### `stats.size` \* Type: {number|bigint} The size of the file in bytes. If the underlying file system does not support getting the size of the file, this will be `0`. #### `stats.blksize` \* Type: {number|bigint} The file system block size for i/o operations. #### `stats.blocks` \* Type: {number|bigint} The number of blocks allocated for this file. #### `stats.atimeMs` \* Type: {number|bigint} The timestamp indicating the last time this file was accessed expressed in milliseconds since the POSIX Epoch. #### `stats.mtimeMs` \* Type: {number|bigint} The timestamp indicating the last time this file was modified expressed in milliseconds since the POSIX Epoch. #### `stats.ctimeMs` \* Type: {number|bigint} The timestamp indicating the last time the file status was changed expressed in milliseconds since the POSIX Epoch. #### `stats.birthtimeMs` \* Type: {number|bigint} The timestamp indicating the creation time of this file expressed in milliseconds since the POSIX Epoch. #### `stats.atimeNs` \* Type: {bigint} Only present when `bigint: true` is passed into the method that generates the object. The timestamp indicating the last time this file was accessed expressed in nanoseconds since the POSIX Epoch. #### `stats.mtimeNs` \* Type: {bigint} Only present when `bigint: true` is passed into the method that generates the object. The timestamp indicating the last time this file was modified expressed in nanoseconds since the POSIX Epoch. #### `stats.ctimeNs` \* Type: {bigint} Only present when `bigint: true` is passed into the method that generates the object. The timestamp indicating the last time the file status was changed expressed in nanoseconds since the POSIX Epoch. #### `stats.birthtimeNs` \* Type: {bigint} Only present when `bigint: true` is passed into the method that generates the object. The timestamp indicating the creation time of this file expressed in nanoseconds since the POSIX Epoch. #### `stats.atime` \* Type: {Date} The timestamp indicating the last time this file was accessed. #### `stats.mtime` \* Type: {Date} The timestamp indicating the last time this file was modified. #### `stats.ctime` \* Type: {Date} The timestamp indicating the last time the file status was changed. #### `stats.birthtime` \* Type: {Date} The timestamp indicating the creation time of this file. #### Stat time values The `atimeMs`, `mtimeMs`, `ctimeMs`, `birthtimeMs` properties are numeric values that hold the corresponding times in milliseconds. Their precision is platform specific. When `bigint: true` is passed into the method that generates the object, the properties will be [bigints][], otherwise they will be [numbers][MDN-Number]. The `atimeNs`, `mtimeNs`, `ctimeNs`, `birthtimeNs` properties are [bigints][] that hold the corresponding times in nanoseconds. They are only present when `bigint: true` is passed into the method that generates the object. Their precision is platform specific. `atime`, `mtime`, `ctime`, and `birthtime` are [`Date`][MDN-Date] object alternate representations of the various times. The `Date` and number values are not connected. Assigning a new number value, or mutating the `Date` value, will not be reflected in the corresponding alternate representation. The times in the stat object have the following semantics: \* `atime` "Access Time": Time when file data last accessed. Changed by the mknod(2), utimes(2), and read(2) system calls. \* `mtime` "Modified Time": Time when file data last modified. Changed by the mknod(2), utimes(2), and write(2) system calls. \* `ctime` "Change Time": Time when file status was last changed (inode data modification). Changed by the chmod(2), chown(2), link(2), mknod(2), rename(2), unlink(2), utimes(2), read(2), and write(2) system calls. \* `birthtime` "Birth Time": Time of file creation. Set once when the file is created. On file systems where birthtime is not available, this field may instead hold either the `ctime` or `1970-01-01T00:00Z` (ie, Unix epoch timestamp `0`). This value may be greater than `atime` | https://github.com/nodejs/node/blob/main//doc/api/fs.md | main | nodejs | [
-0.06319369375705719,
0.06919024139642715,
-0.04906132072210312,
0.023328520357608795,
0.004600484389811754,
-0.11959859728813171,
-0.0431540310382843,
0.13402336835861206,
0.042757462710142136,
0.05659954249858856,
-0.003616094123572111,
0.05090523138642311,
-0.04629414528608322,
-0.04503... | 0.107019 |
read(2), and write(2) system calls. \* `birthtime` "Birth Time": Time of file creation. Set once when the file is created. On file systems where birthtime is not available, this field may instead hold either the `ctime` or `1970-01-01T00:00Z` (ie, Unix epoch timestamp `0`). This value may be greater than `atime` or `mtime` in this case. On Darwin and other FreeBSD variants, also set if the `atime` is explicitly set to an earlier value than the current `birthtime` using the utimes(2) system call. Prior to Node.js 0.12, the `ctime` held the `birthtime` on Windows systems. As of 0.12, `ctime` is not "creation time", and on Unix systems, it never was. ### Class: `fs.StatFs` Provides information about a mounted file system. Objects returned from [`fs.statfs()`][] and its synchronous counterpart are of this type. If `bigint` in the `options` passed to those methods is `true`, the numeric values will be `bigint` instead of `number`. ```console StatFs { type: 1397114950, bsize: 4096, blocks: 121938943, bfree: 61058895, bavail: 61058895, files: 999, ffree: 1000000 } ``` `bigint` version: ```console StatFs { type: 1397114950n, bsize: 4096n, blocks: 121938943n, bfree: 61058895n, bavail: 61058895n, files: 999n, ffree: 1000000n } ``` #### `statfs.bavail` \* Type: {number|bigint} Free blocks available to unprivileged users. #### `statfs.bfree` \* Type: {number|bigint} Free blocks in file system. #### `statfs.blocks` \* Type: {number|bigint} Total data blocks in file system. #### `statfs.bsize` \* Type: {number|bigint} Optimal transfer block size. #### `statfs.ffree` \* Type: {number|bigint} Free file nodes in file system. #### `statfs.files` \* Type: {number|bigint} Total file nodes in file system. #### `statfs.type` \* Type: {number|bigint} Type of file system. ### Class: `fs.Utf8Stream` > Stability: 1 - Experimental An optimized UTF-8 stream writer that allows for flushing all the internal buffering on demand. It handles `EAGAIN` errors correctly, allowing for customization, for example, by dropping content if the disk is busy. #### Event: `'close'` The `'close'` event is emitted when the stream is fully closed. #### Event: `'drain'` The `'drain'` event is emitted when the internal buffer has drained sufficiently to allow continued writing. #### Event: `'drop'` The `'drop'` event is emitted when the maximal length is reached and that data will not be written. The data that was dropped is passed as the first argument to the event handler. #### Event: `'error'` The `'error'` event is emitted when an error occurs. #### Event: `'finish'` The `'finish'` event is emitted when the stream has been ended and all data has been flushed to the underlying file. #### Event: `'ready'` The `'ready'` event is emitted when the stream is ready to accept writes. #### Event: `'write'` The `'write'` event is emitted when a write operation has completed. The number of bytes written is passed as the first argument to the event handler. #### `new fs.Utf8Stream([options])` \* `options` {Object} \* `append`: {boolean} Appends writes to dest file instead of truncating it. \*\*Default\*\*: `true`. \* `contentMode`: {string} Which type of data you can send to the write function, supported values are `'utf8'` or `'buffer'`. \*\*Default\*\*: `'utf8'`. \* `dest`: {string} A path to a file to be written to (mode controlled by the append option). \* `fd`: {number} A file descriptor, something that is returned by `fs.open()` or `fs.openSync()`. \* `fs`: {Object} An object that has the same API as the `fs` module, useful for mocking, testing, or customizing the behavior of the stream. \* `fsync`: {boolean} Perform a `fs.fsyncSync()` every time a write is completed. \* `maxLength`: {number} The maximum length of the internal buffer. If a write operation would cause the buffer to exceed `maxLength`, the data written is dropped and a drop event is emitted with the dropped | https://github.com/nodejs/node/blob/main//doc/api/fs.md | main | nodejs | [
-0.08744477480649948,
0.02987709827721119,
-0.057180602103471756,
0.0562436543405056,
0.10563507676124573,
-0.015736788511276245,
-0.0396164245903492,
0.09965778887271881,
0.08467429131269455,
0.057379353791475296,
0.017747709527611732,
-0.008485612459480762,
-0.0072979796677827835,
-0.063... | 0.077286 |
of the stream. \* `fsync`: {boolean} Perform a `fs.fsyncSync()` every time a write is completed. \* `maxLength`: {number} The maximum length of the internal buffer. If a write operation would cause the buffer to exceed `maxLength`, the data written is dropped and a drop event is emitted with the dropped data \* `maxWrite`: {number} The maximum number of bytes that can be written; \*\*Default\*\*: `16384` \* `minLength`: {number} The minimum length of the internal buffer that is required to be full before flushing. \* `mkdir`: {boolean} Ensure directory for `dest` file exists when true. \*\*Default\*\*: `false`. \* `mode`: {number|string} Specify the creating file mode (see `fs.open()`). \* `periodicFlush`: {number} Calls flush every `periodicFlush` milliseconds. \* `retryEAGAIN` {Function} A function that will be called when `write()`, `writeSync()`, or `flushSync()` encounters an `EAGAIN` or `EBUSY` error. If the return value is `true` the operation will be retried, otherwise it will bubble the error. The `err` is the error that caused this function to be called, `writeBufferLen` is the length of the buffer that was written, and `remainingBufferLen` is the length of the remaining buffer that the stream did not try to write. \* `err` {any} An error or `null`. \* `writeBufferLen` {number} \* `remainingBufferLen`: {number} \* `sync`: {boolean} Perform writes synchronously. #### `utf8Stream.append` \* {boolean} Whether the stream is appending to the file or truncating it. #### `utf8Stream.contentMode` \* {string} The type of data that can be written to the stream. Supported values are `'utf8'` or `'buffer'`. \*\*Default\*\*: `'utf8'`. #### `utf8Stream.destroy()` Close the stream immediately, without flushing the internal buffer. #### `utf8Stream.end()` Close the stream gracefully, flushing the internal buffer before closing. #### `utf8Stream.fd` \* {number} The file descriptor that is being written to. #### `utf8Stream.file` \* {string} The file that is being written to. #### `utf8Stream.flush(callback)` \* `callback` {Function} \* `err` {Error|null} An error if the flush failed, otherwise `null`. Writes the current buffer to the file if a write was not in progress. Do nothing if `minLength` is zero or if it is already writing. #### `utf8Stream.flushSync()` Flushes the buffered data synchronously. This is a costly operation. #### `utf8Stream.fsync` \* {boolean} Whether the stream is performing a `fs.fsyncSync()` after every write operation. #### `utf8Stream.maxLength` \* {number} The maximum length of the internal buffer. If a write operation would cause the buffer to exceed `maxLength`, the data written is dropped and a drop event is emitted with the dropped data. #### `utf8Stream.minLength` \* {number} The minimum length of the internal buffer that is required to be full before flushing. #### `utf8Stream.mkdir` \* {boolean} Whether the stream should ensure that the directory for the `dest` file exists. If `true`, it will create the directory if it does not exist. \*\*Default\*\*: `false`. #### `utf8Stream.mode` \* {number|string} The mode of the file that is being written to. #### `utf8Stream.periodicFlush` \* {number} The number of milliseconds between flushes. If set to `0`, no periodic flushes will be performed. #### `utf8Stream.reopen(file)` \* `file`: {string|Buffer|URL} A path to a file to be written to (mode controlled by the append option). Reopen the file in place, useful for log rotation. #### `utf8Stream.sync` \* {boolean} Whether the stream is writing synchronously or asynchronously. #### `utf8Stream.write(data)` \* `data` {string|Buffer} The data to write. \* Returns {boolean} When the `options.contentMode` is set to `'utf8'` when the stream is created, the `data` argument must be a string. If the `contentMode` is set to `'buffer'`, the `data` argument must be a {Buffer}. #### `utf8Stream.writing` \* {boolean} Whether the stream is currently writing data to the file. #### `utf8Stream[Symbol.dispose]()` Calls `utf8Stream.destroy()`. ### Class: `fs.WriteStream` \* Extends {stream.Writable} Instances of {fs.WriteStream} are created and returned | https://github.com/nodejs/node/blob/main//doc/api/fs.md | main | nodejs | [
-0.014007999561727047,
-0.0019259705441072583,
-0.03881753608584404,
0.03093898668885231,
0.00047672484652139246,
-0.11648767441511154,
-0.04276474937796593,
0.10319940000772476,
0.05238441377878189,
0.027188695967197418,
-0.04578966647386551,
0.033427853137254715,
-0.027274318039417267,
-... | 0.12586 |
argument must be a string. If the `contentMode` is set to `'buffer'`, the `data` argument must be a {Buffer}. #### `utf8Stream.writing` \* {boolean} Whether the stream is currently writing data to the file. #### `utf8Stream[Symbol.dispose]()` Calls `utf8Stream.destroy()`. ### Class: `fs.WriteStream` \* Extends {stream.Writable} Instances of {fs.WriteStream} are created and returned using the [`fs.createWriteStream()`][] function. #### Event: `'close'` Emitted when the {fs.WriteStream}'s underlying file descriptor has been closed. #### Event: `'open'` \* `fd` {integer} Integer file descriptor used by the {fs.WriteStream}. Emitted when the {fs.WriteStream}'s file is opened. #### Event: `'ready'` Emitted when the {fs.WriteStream} is ready to be used. Fires immediately after `'open'`. #### `writeStream.bytesWritten` The number of bytes written so far. Does not include data that is still queued for writing. #### `writeStream.close([callback])` \* `callback` {Function} \* `err` {Error} Closes `writeStream`. Optionally accepts a callback that will be executed once the `writeStream` is closed. #### `writeStream.path` The path to the file the stream is writing to as specified in the first argument to [`fs.createWriteStream()`][]. If `path` is passed as a string, then `writeStream.path` will be a string. If `path` is passed as a {Buffer}, then `writeStream.path` will be a {Buffer}. #### `writeStream.pending` \* Type: {boolean} This property is `true` if the underlying file has not been opened yet, i.e. before the `'ready'` event is emitted. ### `fs.constants` \* Type: {Object} Returns an object containing commonly used constants for file system operations. #### FS constants The following constants are exported by `fs.constants` and `fsPromises.constants`. Not every constant will be available on every operating system; this is especially important for Windows, where many of the POSIX specific definitions are not available. For portable applications it is recommended to check for their presence before use. To use more than one constant, use the bitwise OR `|` operator. Example: ```mjs import { open, constants } from 'node:fs'; const { O\_RDWR, O\_CREAT, O\_EXCL, } = constants; open('/path/to/my/file', O\_RDWR | O\_CREAT | O\_EXCL, (err, fd) => { // ... }); ``` ##### File access constants The following constants are meant for use as the `mode` parameter passed to [`fsPromises.access()`][], [`fs.access()`][], and [`fs.accessSync()`][]. | Constant | Description | | --- | --- | | `F_OK` | Flag indicating that the file is visible to the calling process. This is useful for determining if a file exists, but says nothing about `rwx` permissions. Default if no mode is specified. | | `R_OK` | Flag indicating that the file can be read by the calling process. | | `W_OK` | Flag indicating that the file can be written by the calling process. | | `X_OK` | Flag indicating that the file can be executed by the calling process. This has no effect on Windows (will behave like `fs.constants.F_OK`). | The definitions are also available on Windows. ##### File copy constants The following constants are meant for use with [`fs.copyFile()`][]. | Constant | Description | | --- | --- | | `COPYFILE_EXCL` | If present, the copy operation will fail with an error if the destination path already exists. | | `COPYFILE_FICLONE` | If present, the copy operation will attempt to create a copy-on-write reflink. If the underlying platform does not support copy-on-write, then a fallback copy mechanism is used. | | `COPYFILE_FICLONE_FORCE` | If present, the copy operation will attempt to create a copy-on-write reflink. If the underlying platform does not support copy-on-write, then the operation will fail with an error. | The definitions are also available on Windows. ##### File open constants The following constants are meant for use with `fs.open()`. | Constant | Description | | --- | --- | | `O_RDONLY` | Flag indicating to | https://github.com/nodejs/node/blob/main//doc/api/fs.md | main | nodejs | [
-0.0005722132045775652,
0.04595237597823143,
-0.045507535338401794,
0.04745768383145332,
0.04968131706118584,
-0.07587795704603195,
0.01779651641845703,
0.12174596637487411,
0.0625929981470108,
0.029728855937719345,
-0.07271251827478409,
0.05426185205578804,
-0.02087903395295143,
0.0246109... | 0.104658 |
platform does not support copy-on-write, then the operation will fail with an error. | The definitions are also available on Windows. ##### File open constants The following constants are meant for use with `fs.open()`. | Constant | Description | | --- | --- | | `O_RDONLY` | Flag indicating to open a file for read-only access. | | `O_WRONLY` | Flag indicating to open a file for write-only access. | | `O_RDWR` | Flag indicating to open a file for read-write access. | | `O_CREAT` | Flag indicating to create the file if it does not already exist. | | `O_EXCL` | Flag indicating that opening a file should fail if the `O_CREAT` flag is set and the file already exists. | | `O_NOCTTY` | Flag indicating that if path identifies a terminal device, opening the path shall not cause that terminal to become the controlling terminal for the process (if the process does not already have one). | | `O_TRUNC` | Flag indicating that if the file exists and is a regular file, and the file is opened successfully for write access, its length shall be truncated to zero. | | `O_APPEND` | Flag indicating that data will be appended to the end of the file. | | `O_DIRECTORY` | Flag indicating that the open should fail if the path is not a directory. | | `O_NOATIME` | Flag indicating reading accesses to the file system will no longer result in an update to the `atime` information associated with the file. This flag is available on Linux operating systems only. | | `O_NOFOLLOW` | Flag indicating that the open should fail if the path is a symbolic link. | | `O_SYNC` | Flag indicating that the file is opened for synchronized I/O with write operations waiting for file integrity. | | `O_DSYNC` | Flag indicating that the file is opened for synchronized I/O with write operations waiting for data integrity. | | `O_SYMLINK` | Flag indicating to open the symbolic link itself rather than the resource it is pointing to. | | `O_DIRECT` | When set, an attempt will be made to minimize caching effects of file I/O. | | `O_NONBLOCK` | Flag indicating to open the file in nonblocking mode when possible. | | `UV_FS_O_FILEMAP` | When set, a memory file mapping is used to access the file. This flag is available on Windows operating systems only. On other operating systems, this flag is ignored. | On Windows, only `O\_APPEND`, `O\_CREAT`, `O\_EXCL`, `O\_RDONLY`, `O\_RDWR`, `O\_TRUNC`, `O\_WRONLY`, and `UV\_FS\_O\_FILEMAP` are available. ##### File type constants The following constants are meant for use with the {fs.Stats} object's `mode` property for determining a file's type. | Constant | Description | | --- | --- | | `S_IFMT` | Bit mask used to extract the file type code. | | `S_IFREG` | File type constant for a regular file. | | `S_IFDIR` | File type constant for a directory. | | `S_IFCHR` | File type constant for a character-oriented device file. | | `S_IFBLK` | File type constant for a block-oriented device file. | | `S_IFIFO` | File type constant for a FIFO/pipe. | | `S_IFLNK` | File type constant for a symbolic link. | | `S_IFSOCK` | File type constant for a socket. | On Windows, only `S\_IFCHR`, `S\_IFDIR`, `S\_IFLNK`, `S\_IFMT`, and `S\_IFREG`, are available. ##### File mode constants The following constants are meant for use with the {fs.Stats} object's `mode` property for determining the access permissions for a file. | Constant | Description | | --- | --- | | `S_IRWXU` | File mode indicating readable, writable, and executable by | https://github.com/nodejs/node/blob/main//doc/api/fs.md | main | nodejs | [
-0.042779263108968735,
-0.0528806708753109,
-0.0731196403503418,
0.05789949372410774,
0.028662951663136482,
-0.06457138806581497,
0.007788362447172403,
0.10275744646787643,
0.022366443648934364,
0.023956725373864174,
0.052687112241983414,
0.0038362545892596245,
-0.03570587933063507,
-0.033... | 0.076238 |
and `S\_IFREG`, are available. ##### File mode constants The following constants are meant for use with the {fs.Stats} object's `mode` property for determining the access permissions for a file. | Constant | Description | | --- | --- | | `S_IRWXU` | File mode indicating readable, writable, and executable by owner. | | `S_IRUSR` | File mode indicating readable by owner. | | `S_IWUSR` | File mode indicating writable by owner. | | `S_IXUSR` | File mode indicating executable by owner. | | `S_IRWXG` | File mode indicating readable, writable, and executable by group. | | `S_IRGRP` | File mode indicating readable by group. | | `S_IWGRP` | File mode indicating writable by group. | | `S_IXGRP` | File mode indicating executable by group. | | `S_IRWXO` | File mode indicating readable, writable, and executable by others. | | `S_IROTH` | File mode indicating readable by others. | | `S_IWOTH` | File mode indicating writable by others. | | `S_IXOTH` | File mode indicating executable by others. | On Windows, only `S\_IRUSR` and `S\_IWUSR` are available. ## Notes ### Ordering of callback and promise-based operations Because they are executed asynchronously by the underlying thread pool, there is no guaranteed ordering when using either the callback or promise-based methods. For example, the following is prone to error because the `fs.stat()` operation might complete before the `fs.rename()` operation: ```js const fs = require('node:fs'); fs.rename('/tmp/hello', '/tmp/world', (err) => { if (err) throw err; console.log('renamed complete'); }); fs.stat('/tmp/world', (err, stats) => { if (err) throw err; console.log(`stats: ${JSON.stringify(stats)}`); }); ``` It is important to correctly order the operations by awaiting the results of one before invoking the other: ```mjs import { rename, stat } from 'node:fs/promises'; const oldPath = '/tmp/hello'; const newPath = '/tmp/world'; try { await rename(oldPath, newPath); const stats = await stat(newPath); console.log(`stats: ${JSON.stringify(stats)}`); } catch (error) { console.error('there was an error:', error.message); } ``` ```cjs const { rename, stat } = require('node:fs/promises'); (async function(oldPath, newPath) { try { await rename(oldPath, newPath); const stats = await stat(newPath); console.log(`stats: ${JSON.stringify(stats)}`); } catch (error) { console.error('there was an error:', error.message); } })('/tmp/hello', '/tmp/world'); ``` Or, when using the callback APIs, move the `fs.stat()` call into the callback of the `fs.rename()` operation: ```mjs import { rename, stat } from 'node:fs'; rename('/tmp/hello', '/tmp/world', (err) => { if (err) throw err; stat('/tmp/world', (err, stats) => { if (err) throw err; console.log(`stats: ${JSON.stringify(stats)}`); }); }); ``` ```cjs const { rename, stat } = require('node:fs/promises'); rename('/tmp/hello', '/tmp/world', (err) => { if (err) throw err; stat('/tmp/world', (err, stats) => { if (err) throw err; console.log(`stats: ${JSON.stringify(stats)}`); }); }); ``` ### File paths Most `fs` operations accept file paths that may be specified in the form of a string, a {Buffer}, or a {URL} object using the `file:` protocol. #### String paths String paths are interpreted as UTF-8 character sequences identifying the absolute or relative filename. Relative paths will be resolved relative to the current working directory as determined by calling `process.cwd()`. Example using an absolute path on POSIX: ```mjs import { open } from 'node:fs/promises'; let fd; try { fd = await open('/open/some/file.txt', 'r'); // Do something with the file } finally { await fd?.close(); } ``` Example using a relative path on POSIX (relative to `process.cwd()`): ```mjs import { open } from 'node:fs/promises'; let fd; try { fd = await open('file.txt', 'r'); // Do something with the file } finally { await fd?.close(); } ``` #### File URL paths For most `node:fs` module functions, the `path` or `filename` argument may be passed as a {URL} object using the `file:` protocol. ```mjs import { readFileSync } from 'node:fs'; readFileSync(new URL('file:///tmp/hello')); | https://github.com/nodejs/node/blob/main//doc/api/fs.md | main | nodejs | [
-0.02213973179459572,
0.03404217213392258,
-0.13677909970283508,
0.036536797881126404,
0.0539761483669281,
-0.006733662914484739,
0.02623976767063141,
0.10291536897420883,
-0.06359785795211792,
0.0016582681564614177,
0.10486911982297897,
-0.0411541610956192,
0.004651276860386133,
-0.006541... | 0.170331 |
await open('file.txt', 'r'); // Do something with the file } finally { await fd?.close(); } ``` #### File URL paths For most `node:fs` module functions, the `path` or `filename` argument may be passed as a {URL} object using the `file:` protocol. ```mjs import { readFileSync } from 'node:fs'; readFileSync(new URL('file:///tmp/hello')); ``` `file:` URLs are always absolute paths. ##### Platform-specific considerations On Windows, `file:` {URL}s with a host name convert to UNC paths, while `file:` {URL}s with drive letters convert to local absolute paths. `file:` {URL}s with no host name and no drive letter will result in an error: ```mjs import { readFileSync } from 'node:fs'; // On Windows : // - WHATWG file URLs with hostname convert to UNC path // file://hostname/p/a/t/h/file => \\hostname\p\a\t\h\file readFileSync(new URL('file://hostname/p/a/t/h/file')); // - WHATWG file URLs with drive letters convert to absolute path // file:///C:/tmp/hello => C:\tmp\hello readFileSync(new URL('file:///C:/tmp/hello')); // - WHATWG file URLs without hostname must have a drive letters readFileSync(new URL('file:///notdriveletter/p/a/t/h/file')); readFileSync(new URL('file:///c/p/a/t/h/file')); // TypeError [ERR\_INVALID\_FILE\_URL\_PATH]: File URL path must be absolute ``` `file:` {URL}s with drive letters must use `:` as a separator just after the drive letter. Using another separator will result in an error. On all other platforms, `file:` {URL}s with a host name are unsupported and will result in an error: ```mjs import { readFileSync } from 'node:fs'; // On other platforms: // - WHATWG file URLs with hostname are unsupported // file://hostname/p/a/t/h/file => throw! readFileSync(new URL('file://hostname/p/a/t/h/file')); // TypeError [ERR\_INVALID\_FILE\_URL\_PATH]: must be absolute // - WHATWG file URLs convert to absolute path // file:///tmp/hello => /tmp/hello readFileSync(new URL('file:///tmp/hello')); ``` A `file:` {URL} having encoded slash characters will result in an error on all platforms: ```mjs import { readFileSync } from 'node:fs'; // On Windows readFileSync(new URL('file:///C:/p/a/t/h/%2F')); readFileSync(new URL('file:///C:/p/a/t/h/%2f')); /\* TypeError [ERR\_INVALID\_FILE\_URL\_PATH]: File URL path must not include encoded \ or / characters \*/ // On POSIX readFileSync(new URL('file:///p/a/t/h/%2F')); readFileSync(new URL('file:///p/a/t/h/%2f')); /\* TypeError [ERR\_INVALID\_FILE\_URL\_PATH]: File URL path must not include encoded / characters \*/ ``` On Windows, `file:` {URL}s having encoded backslash will result in an error: ```mjs import { readFileSync } from 'node:fs'; // On Windows readFileSync(new URL('file:///C:/path/%5C')); readFileSync(new URL('file:///C:/path/%5c')); /\* TypeError [ERR\_INVALID\_FILE\_URL\_PATH]: File URL path must not include encoded \ or / characters \*/ ``` #### Buffer paths Paths specified using a {Buffer} are useful primarily on certain POSIX operating systems that treat file paths as opaque byte sequences. On such systems, it is possible for a single file path to contain sub-sequences that use multiple character encodings. As with string paths, {Buffer} paths may be relative or absolute: Example using an absolute path on POSIX: ```mjs import { open } from 'node:fs/promises'; import { Buffer } from 'node:buffer'; let fd; try { fd = await open(Buffer.from('/open/some/file.txt'), 'r'); // Do something with the file } finally { await fd?.close(); } ``` #### Per-drive working directories on Windows On Windows, Node.js follows the concept of per-drive working directory. This behavior can be observed when using a drive path without a backslash. For example `fs.readdirSync('C:\\')` can potentially return a different result than `fs.readdirSync('C:')`. For more information, see [this MSDN page][MSDN-Rel-Path]. ### File descriptors On POSIX systems, for every process, the kernel maintains a table of currently open files and resources. Each open file is assigned a simple numeric identifier called a \_file descriptor\_. At the system-level, all file system operations use these file descriptors to identify and track each specific file. Windows systems use a different but conceptually similar mechanism for tracking resources. To simplify things for users, Node.js abstracts away the differences between operating systems and assigns all open files a numeric file descriptor. The callback-based `fs.open()`, and synchronous | https://github.com/nodejs/node/blob/main//doc/api/fs.md | main | nodejs | [
-0.04635511338710785,
0.05611000210046768,
-0.03869996592402458,
0.07482852786779404,
0.014365830458700657,
-0.02696978859603405,
-0.07711312174797058,
0.125924751162529,
0.016241297125816345,
0.04158945381641388,
-0.04142739251255989,
0.056745097041130066,
0.003147432580590248,
0.01975193... | 0.056545 |
use these file descriptors to identify and track each specific file. Windows systems use a different but conceptually similar mechanism for tracking resources. To simplify things for users, Node.js abstracts away the differences between operating systems and assigns all open files a numeric file descriptor. The callback-based `fs.open()`, and synchronous `fs.openSync()` methods open a file and allocate a new file descriptor. Once allocated, the file descriptor may be used to read data from, write data to, or request information about the file. Operating systems limit the number of file descriptors that may be open at any given time so it is critical to close the descriptor when operations are completed. Failure to do so will result in a memory leak that will eventually cause an application to crash. ```mjs import { open, close, fstat } from 'node:fs'; function closeFd(fd) { close(fd, (err) => { if (err) throw err; }); } open('/open/some/file.txt', 'r', (err, fd) => { if (err) throw err; try { fstat(fd, (err, stat) => { if (err) { closeFd(fd); throw err; } // use stat closeFd(fd); }); } catch (err) { closeFd(fd); throw err; } }); ``` The promise-based APIs use a {FileHandle} object in place of the numeric file descriptor. These objects are better managed by the system to ensure that resources are not leaked. However, it is still required that they are closed when operations are completed: ```mjs import { open } from 'node:fs/promises'; let file; try { file = await open('/open/some/file.txt', 'r'); const stat = await file.stat(); // use stat } finally { await file.close(); } ``` ### Threadpool usage All callback and promise-based file system APIs (with the exception of `fs.FSWatcher()`) use libuv's threadpool. This can have surprising and negative performance implications for some applications. See the [`UV\_THREADPOOL\_SIZE`][] documentation for more information. ### File system flags The following flags are available wherever the `flag` option takes a string. \* `'a'`: Open file for appending. The file is created if it does not exist. \* `'ax'`: Like `'a'` but fails if the path exists. \* `'a+'`: Open file for reading and appending. The file is created if it does not exist. \* `'ax+'`: Like `'a+'` but fails if the path exists. \* `'as'`: Open file for appending in synchronous mode. The file is created if it does not exist. \* `'as+'`: Open file for reading and appending in synchronous mode. The file is created if it does not exist. \* `'r'`: Open file for reading. An exception occurs if the file does not exist. \* `'rs'`: Open file for reading in synchronous mode. An exception occurs if the file does not exist. \* `'r+'`: Open file for reading and writing. An exception occurs if the file does not exist. \* `'rs+'`: Open file for reading and writing in synchronous mode. Instructs the operating system to bypass the local file system cache. This is primarily useful for opening files on NFS mounts as it allows skipping the potentially stale local cache. It has a very real impact on I/O performance so using this flag is not recommended unless it is needed. This doesn't turn `fs.open()` or `fsPromises.open()` into a synchronous blocking call. If synchronous operation is desired, something like `fs.openSync()` should be used. \* `'w'`: Open file for writing. The file is created (if it does not exist) or truncated (if it exists). \* `'wx'`: Like `'w'` but fails if the path exists. \* `'w+'`: Open file for reading and writing. The file is created (if it does not exist) or truncated (if it exists). \* `'wx+'`: Like `'w+'` but fails if the path exists. `flag` | https://github.com/nodejs/node/blob/main//doc/api/fs.md | main | nodejs | [
-0.04599897190928459,
0.02149282768368721,
-0.07986567914485931,
0.07573185861110687,
0.1036345586180687,
-0.05678226053714752,
-0.031403910368680954,
0.09609080851078033,
0.11396347731351852,
0.02286604233086109,
-0.04568786174058914,
0.1063603088259697,
-0.07950527220964432,
-0.044150326... | 0.180459 |
not exist) or truncated (if it exists). \* `'wx'`: Like `'w'` but fails if the path exists. \* `'w+'`: Open file for reading and writing. The file is created (if it does not exist) or truncated (if it exists). \* `'wx+'`: Like `'w+'` but fails if the path exists. `flag` can also be a number as documented by open(2); commonly used constants are available from `fs.constants`. On Windows, flags are translated to their equivalent ones where applicable, e.g. `O\_WRONLY` to `FILE\_GENERIC\_WRITE`, or `O\_EXCL|O\_CREAT` to `CREATE\_NEW`, as accepted by `CreateFileW`. The exclusive flag `'x'` (`O\_EXCL` flag in open(2)) causes the operation to return an error if the path already exists. On POSIX, if the path is a symbolic link, using `O\_EXCL` returns an error even if the link is to a path that does not exist. The exclusive flag might not work with network file systems. On Linux, positional writes don't work when the file is opened in append mode. The kernel ignores the position argument and always appends the data to the end of the file. Modifying a file rather than replacing it may require the `flag` option to be set to `'r+'` rather than the default `'w'`. The behavior of some flags are platform-specific. As such, opening a directory on macOS and Linux with the `'a+'` flag, as in the example below, will return an error. In contrast, on Windows and FreeBSD, a file descriptor or a `FileHandle` will be returned. ```js // macOS and Linux fs.open('', 'a+', (err, fd) => { // => [Error: EISDIR: illegal operation on a directory, open ] }); // Windows and FreeBSD fs.open('', 'a+', (err, fd) => { // => null, }); ``` On Windows, opening an existing hidden file using the `'w'` flag (either through `fs.open()`, `fs.writeFile()`, or `fsPromises.open()`) will fail with `EPERM`. Existing hidden files can be opened for writing with the `'r+'` flag. A call to `fs.ftruncate()` or `filehandle.truncate()` can be used to reset the file contents. [#25741]: https://github.com/nodejs/node/issues/25741 [Common System Errors]: errors.md#common-system-errors [FS constants]: #fs-constants [File access constants]: #file-access-constants [File modes]: #file-modes [MDN-Date]: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global\_Objects/Date [MDN-Number]: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Guide/Data\_structures#number\_type [MSDN-Rel-Path]: https://docs.microsoft.com/en-us/windows/desktop/FileIO/naming-a-file#fully-qualified-vs-relative-paths [MSDN-Using-Streams]: https://docs.microsoft.com/en-us/windows/desktop/FileIO/using-streams [Naming Files, Paths, and Namespaces]: https://docs.microsoft.com/en-us/windows/desktop/FileIO/naming-a-file [`AHAFS`]: https://developer.ibm.com/articles/au-aix\_event\_infrastructure/ [`Buffer.byteLength`]: buffer.md#static-method-bufferbytelengthstring-encoding [`FSEvents`]: https://developer.apple.com/documentation/coreservices/file\_system\_events [`Number.MAX\_SAFE\_INTEGER`]: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global\_Objects/Number/MAX\_SAFE\_INTEGER [`ReadDirectoryChangesW`]: https://docs.microsoft.com/en-us/windows/desktop/api/winbase/nf-winbase-readdirectorychangesw [`UV\_THREADPOOL\_SIZE`]: cli.md#uv\_threadpool\_sizesize [`event ports`]: https://illumos.org/man/port\_create [`filehandle.createReadStream()`]: #filehandlecreatereadstreamoptions [`filehandle.createWriteStream()`]: #filehandlecreatewritestreamoptions [`filehandle.writeFile()`]: #filehandlewritefiledata-options [`fs.access()`]: #fsaccesspath-mode-callback [`fs.accessSync()`]: #fsaccesssyncpath-mode [`fs.chmod()`]: #fschmodpath-mode-callback [`fs.chown()`]: #fschownpath-uid-gid-callback [`fs.copyFile()`]: #fscopyfilesrc-dest-mode-callback [`fs.copyFileSync()`]: #fscopyfilesyncsrc-dest-mode [`fs.createReadStream()`]: #fscreatereadstreampath-options [`fs.createWriteStream()`]: #fscreatewritestreampath-options [`fs.exists()`]: #fsexistspath-callback [`fs.fstat()`]: #fsfstatfd-options-callback [`fs.ftruncate()`]: #fsftruncatefd-len-callback [`fs.futimes()`]: #fsfutimesfd-atime-mtime-callback [`fs.lstat()`]: #fslstatpath-options-callback [`fs.lutimes()`]: #fslutimespath-atime-mtime-callback [`fs.mkdir()`]: #fsmkdirpath-options-callback [`fs.mkdtemp()`]: #fsmkdtempprefix-options-callback [`fs.open()`]: #fsopenpath-flags-mode-callback [`fs.opendir()`]: #fsopendirpath-options-callback [`fs.opendirSync()`]: #fsopendirsyncpath-options [`fs.read()`]: #fsreadfd-buffer-offset-length-position-callback [`fs.readFile()`]: #fsreadfilepath-options-callback [`fs.readFileSync()`]: #fsreadfilesyncpath-options [`fs.readdir()`]: #fsreaddirpath-options-callback [`fs.readdirSync()`]: #fsreaddirsyncpath-options [`fs.readv()`]: #fsreadvfd-buffers-position-callback [`fs.realpath()`]: #fsrealpathpath-options-callback [`fs.rm()`]: #fsrmpath-options-callback [`fs.rmSync()`]: #fsrmsyncpath-options [`fs.rmdir()`]: #fsrmdirpath-options-callback [`fs.stat()`]: #fsstatpath-options-callback [`fs.statfs()`]: #fsstatfspath-options-callback [`fs.symlink()`]: #fssymlinktarget-path-type-callback [`fs.utimes()`]: #fsutimespath-atime-mtime-callback [`fs.watch()`]: #fswatchfilename-options-listener [`fs.write(fd, buffer...)`]: #fswritefd-buffer-offset-length-position-callback [`fs.write(fd, string...)`]: #fswritefd-string-position-encoding-callback [`fs.writeFile()`]: #fswritefilefile-data-options-callback [`fs.writev()`]: #fswritevfd-buffers-position-callback [`fsPromises.access()`]: #fspromisesaccesspath-mode [`fsPromises.copyFile()`]: #fspromisescopyfilesrc-dest-mode [`fsPromises.mkdtemp()`]: #fspromisesmkdtempprefix-options [`fsPromises.open()`]: #fspromisesopenpath-flags-mode [`fsPromises.opendir()`]: #fspromisesopendirpath-options [`fsPromises.rm()`]: #fspromisesrmpath-options [`fsPromises.stat()`]: #fspromisesstatpath-options [`fsPromises.utimes()`]: #fspromisesutimespath-atime-mtime [`inotify(7)`]: https://man7.org/linux/man-pages/man7/inotify.7.html [`kqueue(2)`]: https://www.freebsd.org/cgi/man.cgi?query=kqueue&sektion=2 [`minimatch`]: https://github.com/isaacs/minimatch [`util.promisify()`]: util.md#utilpromisifyoriginal [bigints]: https://tc39.github.io/proposal-bigint [caveats]: #caveats [chcp]: https://ss64.com/nt/chcp.html [inode]: https://en.wikipedia.org/wiki/Inode [support of file system `flags`]: #file-system-flags | https://github.com/nodejs/node/blob/main//doc/api/fs.md | main | nodejs | [
-0.08237000554800034,
-0.019513921812176704,
-0.05529586225748062,
0.07654809206724167,
0.01407939475029707,
-0.08968087285757065,
0.054587095975875854,
0.07083144038915634,
0.04436826705932617,
0.012311429716646671,
0.05852873995900154,
-0.0035598056856542826,
0.02447189949452877,
0.00811... | 0.126909 |
# Process The `process` object provides information about, and control over, the current Node.js process. ```mjs import process from 'node:process'; ``` ```cjs const process = require('node:process'); ``` ## Process events The `process` object is an instance of [`EventEmitter`][]. ### Event: `'beforeExit'` The `'beforeExit'` event is emitted when Node.js empties its event loop and has no additional work to schedule. Normally, the Node.js process will exit when there is no work scheduled, but a listener registered on the `'beforeExit'` event can make asynchronous calls, and thereby cause the Node.js process to continue. The listener callback function is invoked with the value of [`process.exitCode`][] passed as the only argument. The `'beforeExit'` event is \_not\_ emitted for conditions causing explicit termination, such as calling [`process.exit()`][] or uncaught exceptions. The `'beforeExit'` should \_not\_ be used as an alternative to the `'exit'` event unless the intention is to schedule additional work. ```mjs import process from 'node:process'; process.on('beforeExit', (code) => { console.log('Process beforeExit event with code: ', code); }); process.on('exit', (code) => { console.log('Process exit event with code: ', code); }); console.log('This message is displayed first.'); // Prints: // This message is displayed first. // Process beforeExit event with code: 0 // Process exit event with code: 0 ``` ```cjs const process = require('node:process'); process.on('beforeExit', (code) => { console.log('Process beforeExit event with code: ', code); }); process.on('exit', (code) => { console.log('Process exit event with code: ', code); }); console.log('This message is displayed first.'); // Prints: // This message is displayed first. // Process beforeExit event with code: 0 // Process exit event with code: 0 ``` ### Event: `'disconnect'` If the Node.js process is spawned with an IPC channel (see the [Child Process][] and [Cluster][] documentation), the `'disconnect'` event will be emitted when the IPC channel is closed. ### Event: `'exit'` \* `code` {integer} The `'exit'` event is emitted when the Node.js process is about to exit as a result of either: \* The `process.exit()` method being called explicitly; \* The Node.js event loop no longer having any additional work to perform. There is no way to prevent the exiting of the event loop at this point, and once all `'exit'` listeners have finished running the Node.js process will terminate. The listener callback function is invoked with the exit code specified either by the [`process.exitCode`][] property, or the `exitCode` argument passed to the [`process.exit()`][] method. ```mjs import process from 'node:process'; process.on('exit', (code) => { console.log(`About to exit with code: ${code}`); }); ``` ```cjs const process = require('node:process'); process.on('exit', (code) => { console.log(`About to exit with code: ${code}`); }); ``` Listener functions \*\*must\*\* only perform \*\*synchronous\*\* operations. The Node.js process will exit immediately after calling the `'exit'` event listeners causing any additional work still queued in the event loop to be abandoned. In the following example, for instance, the timeout will never occur: ```mjs import process from 'node:process'; process.on('exit', (code) => { setTimeout(() => { console.log('This will not run'); }, 0); }); ``` ```cjs const process = require('node:process'); process.on('exit', (code) => { setTimeout(() => { console.log('This will not run'); }, 0); }); ``` ### Event: `'message'` \* `message` { Object | boolean | number | string | null } a parsed JSON object or a serializable primitive value. \* `sendHandle` {net.Server|net.Socket} a [`net.Server`][] or [`net.Socket`][] object, or undefined. If the Node.js process is spawned with an IPC channel (see the [Child Process][] and [Cluster][] documentation), the `'message'` event is emitted whenever a message sent by a parent process using [`childprocess.send()`][] is received by the child process. The message goes through serialization and parsing. The resulting message might not be the same as what is originally sent. If | https://github.com/nodejs/node/blob/main//doc/api/process.md | main | nodejs | [
-0.08048714697360992,
-0.014997819438576698,
0.026660412549972534,
0.07168350368738174,
0.11290401220321655,
-0.02473660744726658,
-0.03937844932079315,
0.02839348092675209,
0.04308680444955826,
-0.007054581772536039,
-0.10734138637781143,
0.07444368302822113,
0.02389288879930973,
-0.03275... | 0.118276 |
channel (see the [Child Process][] and [Cluster][] documentation), the `'message'` event is emitted whenever a message sent by a parent process using [`childprocess.send()`][] is received by the child process. The message goes through serialization and parsing. The resulting message might not be the same as what is originally sent. If the `serialization` option was set to `advanced` used when spawning the process, the `message` argument can contain data that JSON is not able to represent. See [Advanced serialization for `child\_process`][] for more details. ### Event: `'rejectionHandled'` \* `promise` {Promise} The late handled promise. The `'rejectionHandled'` event is emitted whenever a `Promise` has been rejected and an error handler was attached to it (using [`promise.catch()`][], for example) later than one turn of the Node.js event loop. The `Promise` object would have previously been emitted in an `'unhandledRejection'` event, but during the course of processing gained a rejection handler. There is no notion of a top level for a `Promise` chain at which rejections can always be handled. Being inherently asynchronous in nature, a `Promise` rejection can be handled at a future point in time, possibly much later than the event loop turn it takes for the `'unhandledRejection'` event to be emitted. Another way of stating this is that, unlike in synchronous code where there is an ever-growing list of unhandled exceptions, with Promises there can be a growing-and-shrinking list of unhandled rejections. In synchronous code, the `'uncaughtException'` event is emitted when the list of unhandled exceptions grows. In asynchronous code, the `'unhandledRejection'` event is emitted when the list of unhandled rejections grows, and the `'rejectionHandled'` event is emitted when the list of unhandled rejections shrinks. ```mjs import process from 'node:process'; const unhandledRejections = new Map(); process.on('unhandledRejection', (reason, promise) => { unhandledRejections.set(promise, reason); }); process.on('rejectionHandled', (promise) => { unhandledRejections.delete(promise); }); ``` ```cjs const process = require('node:process'); const unhandledRejections = new Map(); process.on('unhandledRejection', (reason, promise) => { unhandledRejections.set(promise, reason); }); process.on('rejectionHandled', (promise) => { unhandledRejections.delete(promise); }); ``` In this example, the `unhandledRejections` `Map` will grow and shrink over time, reflecting rejections that start unhandled and then become handled. It is possible to record such errors in an error log, either periodically (which is likely best for long-running application) or upon process exit (which is likely most convenient for scripts). ### Event: `'workerMessage'` \* `value` {any} A value transmitted using [`postMessageToThread()`][]. \* `source` {number} The transmitting worker thread ID or `0` for the main thread. The `'workerMessage'` event is emitted for any incoming message send by the other party by using [`postMessageToThread()`][]. ### Event: `'uncaughtException'` \* `err` {Error} The uncaught exception. \* `origin` {string} Indicates if the exception originates from an unhandled rejection or from a synchronous error. Can either be `'uncaughtException'` or `'unhandledRejection'`. The latter is used when an exception happens in a `Promise` based async context (or if a `Promise` is rejected) and [`--unhandled-rejections`][] flag set to `strict` or `throw` (which is the default) and the rejection is not handled, or when a rejection happens during the command line entry point's ES module static loading phase. The `'uncaughtException'` event is emitted when an uncaught JavaScript exception bubbles all the way back to the event loop. By default, Node.js handles such exceptions by printing the stack trace to `stderr` and exiting with code 1, overriding any previously set [`process.exitCode`][]. Adding a handler for the `'uncaughtException'` event overrides this default behavior. Alternatively, change the [`process.exitCode`][] in the `'uncaughtException'` handler which will result in the process exiting with the provided exit code. Otherwise, in the presence of such handler the process will exit with 0. ```mjs import process from 'node:process'; import fs from 'node:fs'; process.on('uncaughtException', | https://github.com/nodejs/node/blob/main//doc/api/process.md | main | nodejs | [
-0.048568665981292725,
0.025694018229842186,
0.04973533749580383,
0.07497693598270416,
0.04106703773140907,
-0.07150409370660782,
-0.019687442108988762,
0.04107292741537094,
0.1117621511220932,
-0.01766575314104557,
-0.038852717727422714,
0.05071064829826355,
0.014647465199232101,
0.031509... | 0.126695 |
the `'uncaughtException'` event overrides this default behavior. Alternatively, change the [`process.exitCode`][] in the `'uncaughtException'` handler which will result in the process exiting with the provided exit code. Otherwise, in the presence of such handler the process will exit with 0. ```mjs import process from 'node:process'; import fs from 'node:fs'; process.on('uncaughtException', (err, origin) => { fs.writeSync( process.stderr.fd, `Caught exception: ${err}\n` + `Exception origin: ${origin}\n`, ); }); setTimeout(() => { console.log('This will still run.'); }, 500); // Intentionally cause an exception, but don't catch it. nonexistentFunc(); console.log('This will not run.'); ``` ```cjs const process = require('node:process'); const fs = require('node:fs'); process.on('uncaughtException', (err, origin) => { fs.writeSync( process.stderr.fd, `Caught exception: ${err}\n` + `Exception origin: ${origin}\n`, ); }); setTimeout(() => { console.log('This will still run.'); }, 500); // Intentionally cause an exception, but don't catch it. nonexistentFunc(); console.log('This will not run.'); ``` It is possible to monitor `'uncaughtException'` events without overriding the default behavior to exit the process by installing a `'uncaughtExceptionMonitor'` listener. #### Warning: Using `'uncaughtException'` correctly `'uncaughtException'` is a crude mechanism for exception handling intended to be used only as a last resort. The event \_should not\_ be used as an equivalent to `On Error Resume Next`. Unhandled exceptions inherently mean that an application is in an undefined state. Attempting to resume application code without properly recovering from the exception can cause additional unforeseen and unpredictable issues. Exceptions thrown from within the event handler will not be caught. Instead the process will exit with a non-zero exit code and the stack trace will be printed. This is to avoid infinite recursion. Attempting to resume normally after an uncaught exception can be similar to pulling out the power cord when upgrading a computer. Nine out of ten times, nothing happens. But the tenth time, the system becomes corrupted. The correct use of `'uncaughtException'` is to perform synchronous cleanup of allocated resources (e.g. file descriptors, handles, etc) before shutting down the process. \*\*It is not safe to resume normal operation after `'uncaughtException'`.\*\* To restart a crashed application in a more reliable way, whether `'uncaughtException'` is emitted or not, an external monitor should be employed in a separate process to detect application failures and recover or restart as needed. ### Event: `'uncaughtExceptionMonitor'` \* `err` {Error} The uncaught exception. \* `origin` {string} Indicates if the exception originates from an unhandled rejection or from synchronous errors. Can either be `'uncaughtException'` or `'unhandledRejection'`. The latter is used when an exception happens in a `Promise` based async context (or if a `Promise` is rejected) and [`--unhandled-rejections`][] flag set to `strict` or `throw` (which is the default) and the rejection is not handled, or when a rejection happens during the command line entry point's ES module static loading phase. The `'uncaughtExceptionMonitor'` event is emitted before an `'uncaughtException'` event is emitted or a hook installed via [`process.setUncaughtExceptionCaptureCallback()`][] is called. Installing an `'uncaughtExceptionMonitor'` listener does not change the behavior once an `'uncaughtException'` event is emitted. The process will still crash if no `'uncaughtException'` listener is installed. ```mjs import process from 'node:process'; process.on('uncaughtExceptionMonitor', (err, origin) => { MyMonitoringTool.logSync(err, origin); }); // Intentionally cause an exception, but don't catch it. nonexistentFunc(); // Still crashes Node.js ``` ```cjs const process = require('node:process'); process.on('uncaughtExceptionMonitor', (err, origin) => { MyMonitoringTool.logSync(err, origin); }); // Intentionally cause an exception, but don't catch it. nonexistentFunc(); // Still crashes Node.js ``` ### Event: `'unhandledRejection'` \* `reason` {Error|any} The object with which the promise was rejected (typically an [`Error`][] object). \* `promise` {Promise} The rejected promise. The `'unhandledRejection'` event is emitted whenever a `Promise` is rejected and no error handler is attached to the promise within a turn of the event loop. | https://github.com/nodejs/node/blob/main//doc/api/process.md | main | nodejs | [
-0.026872264221310616,
0.026658937335014343,
-0.02410421334207058,
0.047989699989557266,
0.09686030447483063,
-0.037166617810726166,
-0.07653266191482544,
0.06528998166322708,
0.0763983353972435,
0.03980458527803421,
-0.032750848680734634,
0.013412626460194588,
-0.00914593506604433,
-0.078... | 0.056476 |
### Event: `'unhandledRejection'` \* `reason` {Error|any} The object with which the promise was rejected (typically an [`Error`][] object). \* `promise` {Promise} The rejected promise. The `'unhandledRejection'` event is emitted whenever a `Promise` is rejected and no error handler is attached to the promise within a turn of the event loop. When programming with Promises, exceptions are encapsulated as "rejected promises". Rejections can be caught and handled using [`promise.catch()`][] and are propagated through a `Promise` chain. The `'unhandledRejection'` event is useful for detecting and keeping track of promises that were rejected whose rejections have not yet been handled. ```mjs import process from 'node:process'; process.on('unhandledRejection', (reason, promise) => { console.log('Unhandled Rejection at:', promise, 'reason:', reason); // Application specific logging, throwing an error, or other logic here }); somePromise.then((res) => { return reportToUser(JSON.pasre(res)); // Note the typo (`pasre`) }); // No `.catch()` or `.then()` ``` ```cjs const process = require('node:process'); process.on('unhandledRejection', (reason, promise) => { console.log('Unhandled Rejection at:', promise, 'reason:', reason); // Application specific logging, throwing an error, or other logic here }); somePromise.then((res) => { return reportToUser(JSON.pasre(res)); // Note the typo (`pasre`) }); // No `.catch()` or `.then()` ``` The following will also trigger the `'unhandledRejection'` event to be emitted: ```mjs import process from 'node:process'; function SomeResource() { // Initially set the loaded status to a rejected promise this.loaded = Promise.reject(new Error('Resource not yet loaded!')); } const resource = new SomeResource(); // no .catch or .then on resource.loaded for at least a turn ``` ```cjs const process = require('node:process'); function SomeResource() { // Initially set the loaded status to a rejected promise this.loaded = Promise.reject(new Error('Resource not yet loaded!')); } const resource = new SomeResource(); // no .catch or .then on resource.loaded for at least a turn ``` In this example case, it is possible to track the rejection as a developer error as would typically be the case for other `'unhandledRejection'` events. To address such failures, a non-operational [`.catch(() => { })`][`promise.catch()`] handler may be attached to `resource.loaded`, which would prevent the `'unhandledRejection'` event from being emitted. If an `'unhandledRejection'` event is emitted but not handled it will be raised as an uncaught exception. This alongside other behaviors of `'unhandledRejection'` events can changed via the [`--unhandled-rejections`][] flag. ### Event: `'warning'` \* `warning` {Error} Key properties of the warning are: \* `name` {string} The name of the warning. \*\*Default:\*\* `'Warning'`. \* `message` {string} A system-provided description of the warning. \* `stack` {string} A stack trace to the location in the code where the warning was issued. The `'warning'` event is emitted whenever Node.js emits a process warning. A process warning is similar to an error in that it describes exceptional conditions that are being brought to the user's attention. However, warnings are not part of the normal Node.js and JavaScript error handling flow. Node.js can emit warnings whenever it detects bad coding practices that could lead to sub-optimal application performance, bugs, or security vulnerabilities. ```mjs import process from 'node:process'; process.on('warning', (warning) => { console.warn(warning.name); // Print the warning name console.warn(warning.message); // Print the warning message console.warn(warning.stack); // Print the stack trace }); ``` ```cjs const process = require('node:process'); process.on('warning', (warning) => { console.warn(warning.name); // Print the warning name console.warn(warning.message); // Print the warning message console.warn(warning.stack); // Print the stack trace }); ``` By default, Node.js will print process warnings to `stderr`. The `--no-warnings` command-line option can be used to suppress the default console output but the `'warning'` event will still be emitted by the `process` object. Currently, it is not possible to suppress specific warning types other than deprecation warnings. To suppress deprecation warnings, check out the [`--no-deprecation`][] flag. The following example | https://github.com/nodejs/node/blob/main//doc/api/process.md | main | nodejs | [
-0.06249630078673363,
0.07741951197385788,
0.08033861219882965,
0.08838939666748047,
0.07814156264066696,
-0.038216158747673035,
0.0035263157915323973,
0.04694199189543724,
0.11469060927629471,
-0.015290752984583378,
-0.03842819109559059,
-0.0018020081333816051,
0.047518085688352585,
-0.04... | 0.113858 |
`--no-warnings` command-line option can be used to suppress the default console output but the `'warning'` event will still be emitted by the `process` object. Currently, it is not possible to suppress specific warning types other than deprecation warnings. To suppress deprecation warnings, check out the [`--no-deprecation`][] flag. The following example illustrates the warning that is printed to `stderr` when too many listeners have been added to an event: ```console $ node > events.defaultMaxListeners = 1; > process.on('foo', () => {}); > process.on('foo', () => {}); > (node:38638) MaxListenersExceededWarning: Possible EventEmitter memory leak detected. 2 foo listeners added. Use emitter.setMaxListeners() to increase limit ``` In contrast, the following example turns off the default warning output and adds a custom handler to the `'warning'` event: ```console $ node --no-warnings > const p = process.on('warning', (warning) => console.warn('Do not do that!')); > events.defaultMaxListeners = 1; > process.on('foo', () => {}); > process.on('foo', () => {}); > Do not do that! ``` The `--trace-warnings` command-line option can be used to have the default console output for warnings include the full stack trace of the warning. Launching Node.js using the `--throw-deprecation` command-line flag will cause custom deprecation warnings to be thrown as exceptions. Using the `--trace-deprecation` command-line flag will cause the custom deprecation to be printed to `stderr` along with the stack trace. Using the `--no-deprecation` command-line flag will suppress all reporting of the custom deprecation. The `\*-deprecation` command-line flags only affect warnings that use the name `'DeprecationWarning'`. #### Emitting custom warnings See the [`process.emitWarning()`][process\_emit\_warning] method for issuing custom or application-specific warnings. #### Node.js warning names There are no strict guidelines for warning types (as identified by the `name` property) emitted by Node.js. New types of warnings can be added at any time. A few of the warning types that are most common include: \* `'DeprecationWarning'` - Indicates use of a deprecated Node.js API or feature. Such warnings must include a `'code'` property identifying the [deprecation code][]. \* `'ExperimentalWarning'` - Indicates use of an experimental Node.js API or feature. Such features must be used with caution as they may change at any time and are not subject to the same strict semantic-versioning and long-term support policies as supported features. \* `'MaxListenersExceededWarning'` - Indicates that too many listeners for a given event have been registered on either an `EventEmitter` or `EventTarget`. This is often an indication of a memory leak. \* `'TimeoutOverflowWarning'` - Indicates that a numeric value that cannot fit within a 32-bit signed integer has been provided to either the `setTimeout()` or `setInterval()` functions. \* `'TimeoutNegativeWarning'` - Indicates that a negative number has provided to either the `setTimeout()` or `setInterval()` functions. \* `'TimeoutNaNWarning'` - Indicates that a value which is not a number has provided to either the `setTimeout()` or `setInterval()` functions. \* `'UnsupportedWarning'` - Indicates use of an unsupported option or feature that will be ignored rather than treated as an error. One example is use of the HTTP response status message when using the HTTP/2 compatibility API. ### Event: `'worker'` \* `worker` {Worker} The {Worker} that was created. The `'worker'` event is emitted after a new {Worker} thread has been created. ### Signal events Signal events will be emitted when the Node.js process receives a signal. Please refer to signal(7) for a listing of standard POSIX signal names such as `'SIGINT'`, `'SIGHUP'`, etc. Signals are not available on [`Worker`][] threads. The signal handler will receive the signal's name (`'SIGINT'`, `'SIGTERM'`, etc.) as the first argument. The name of each event will be the uppercase common name for the signal (e.g. `'SIGINT'` for `SIGINT` signals). ```mjs import process from 'node:process'; // Begin reading | https://github.com/nodejs/node/blob/main//doc/api/process.md | main | nodejs | [
0.0690658837556839,
0.028944773599505424,
-0.03026309795677662,
0.10227860510349274,
0.08289776742458344,
0.02448922023177147,
0.042879048734903336,
0.06046184524893761,
0.06053018197417259,
0.03383243456482887,
-0.036390818655490875,
-0.019142935052514076,
-0.017690954729914665,
-0.027708... | 0.068474 |
etc. Signals are not available on [`Worker`][] threads. The signal handler will receive the signal's name (`'SIGINT'`, `'SIGTERM'`, etc.) as the first argument. The name of each event will be the uppercase common name for the signal (e.g. `'SIGINT'` for `SIGINT` signals). ```mjs import process from 'node:process'; // 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.'); }); // Using a single function to handle multiple signals function handle(signal) { console.log(`Received ${signal}`); } process.on('SIGINT', handle); process.on('SIGTERM', handle); ``` ```cjs const process = require('node:process'); // 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.'); }); // Using a single function to handle multiple signals function handle(signal) { console.log(`Received ${signal}`); } process.on('SIGINT', handle); process.on('SIGTERM', handle); ``` \* `'SIGUSR1'` is reserved by Node.js to start the [debugger][]. It's possible to install a listener but doing so might interfere with the debugger. \* `'SIGTERM'` and `'SIGINT'` have default handlers on non-Windows platforms that reset the terminal mode before exiting with code `128 + signal number`. If one of these signals has a listener installed, its default behavior will be removed (Node.js will no longer exit). \* `'SIGPIPE'` is ignored by default. It can have a listener installed. \* `'SIGHUP'` is generated on Windows when the console window is closed, and on other platforms under various similar conditions. See signal(7). It can have a listener installed, however Node.js will be unconditionally terminated by Windows about 10 seconds later. On non-Windows platforms, the default behavior of `SIGHUP` is to terminate Node.js, but once a listener has been installed its default behavior will be removed. \* `'SIGTERM'` is not supported on Windows, it can be listened on. \* `'SIGINT'` from the terminal is supported on all platforms, and can usually be generated with `Ctrl`+`C` (though this may be configurable). It is not generated when [terminal raw mode][] is enabled and `Ctrl`+`C` is used. \* `'SIGBREAK'` is delivered on Windows when `Ctrl`+`Break` is pressed. On non-Windows platforms, it can be listened on, but there is no way to send or generate it. \* `'SIGWINCH'` is delivered when the console has been resized. On Windows, this will only happen on write to the console when the cursor is being moved, or when a readable tty is used in raw mode. \* `'SIGKILL'` cannot have a listener installed, it will unconditionally terminate Node.js on all platforms. \* `'SIGSTOP'` cannot have a listener installed. \* `'SIGBUS'`, `'SIGFPE'`, `'SIGSEGV'`, and `'SIGILL'`, when not raised artificially using kill(2), inherently leave the process in a state from which it is not safe to call JS listeners. Doing so might cause the process to stop responding. \* `0` can be sent to test for the existence of a process, it has no effect if the process exists, but will throw an error if the process does not exist. Windows does not support signals so has no equivalent to termination by signal, but Node.js offers some emulation with [`process.kill()`][], and [`subprocess.kill()`][]: \* Sending `SIGINT`, `SIGTERM`, and `SIGKILL` will cause the unconditional termination of the target process, and afterwards, subprocess will report that the process was terminated by signal. \* Sending signal `0` can be used as a platform independent way to test for the existence of a process. ## `process.abort()` The `process.abort()` method causes the Node.js process to exit immediately and generate a core file. This feature is not available in [`Worker`][] threads. ## `process.allowedNodeEnvironmentFlags` \* Type: {Set} The `process.allowedNodeEnvironmentFlags` property is a special, read-only `Set` of flags allowable within the [`NODE\_OPTIONS`][] | https://github.com/nodejs/node/blob/main//doc/api/process.md | main | nodejs | [
-0.031183522194623947,
-0.05718404799699783,
0.008353542536497116,
-0.006795310880988836,
0.009094499982893467,
-0.013956917449831963,
0.030155960470438004,
0.03723631799221039,
0.07841203361749649,
-0.014394349418580532,
-0.05198206752538681,
-0.016478387638926506,
-0.05701921507716179,
-... | 0.129714 |
for the existence of a process. ## `process.abort()` The `process.abort()` method causes the Node.js process to exit immediately and generate a core file. This feature is not available in [`Worker`][] threads. ## `process.allowedNodeEnvironmentFlags` \* Type: {Set} The `process.allowedNodeEnvironmentFlags` property is a special, read-only `Set` of flags allowable within the [`NODE\_OPTIONS`][] environment variable. `process.allowedNodeEnvironmentFlags` extends `Set`, but overrides `Set.prototype.has` to recognize several different possible flag representations. `process.allowedNodeEnvironmentFlags.has()` will return `true` in the following cases: \* Flags may omit leading single (`-`) or double (`--`) dashes; e.g., `inspect-brk` for `--inspect-brk`, or `r` for `-r`. \* Flags passed through to V8 (as listed in `--v8-options`) may replace one or more \_non-leading\_ dashes for an underscore, or vice-versa; e.g., `--perf\_basic\_prof`, `--perf-basic-prof`, `--perf\_basic-prof`, etc. \* Flags may contain one or more equals (`=`) characters; all characters after and including the first equals will be ignored; e.g., `--stack-trace-limit=100`. \* Flags \_must\_ be allowable within [`NODE\_OPTIONS`][]. When iterating over `process.allowedNodeEnvironmentFlags`, flags will appear only \_once\_; each will begin with one or more dashes. Flags passed through to V8 will contain underscores instead of non-leading dashes: ```mjs import { allowedNodeEnvironmentFlags } from 'node:process'; allowedNodeEnvironmentFlags.forEach((flag) => { // -r // --inspect-brk // --abort\_on\_uncaught\_exception // ... }); ``` ```cjs const { allowedNodeEnvironmentFlags } = require('node:process'); allowedNodeEnvironmentFlags.forEach((flag) => { // -r // --inspect-brk // --abort\_on\_uncaught\_exception // ... }); ``` The methods `add()`, `clear()`, and `delete()` of `process.allowedNodeEnvironmentFlags` do nothing, and will fail silently. If Node.js was compiled \_without\_ [`NODE\_OPTIONS`][] support (shown in [`process.config`][]), `process.allowedNodeEnvironmentFlags` will contain what \_would have\_ been allowable. ## `process.arch` \* Type: {string} The operating system CPU architecture for which the Node.js binary was compiled. Possible values are: `'arm'`, `'arm64'`, `'ia32'`, `'loong64'`, `'mips'`, `'mipsel'`, `'ppc64'`, `'riscv64'`, `'s390'`, `'s390x'`, and `'x64'`. ```mjs import { arch } from 'node:process'; console.log(`This processor architecture is ${arch}`); ``` ```cjs const { arch } = require('node:process'); console.log(`This processor architecture is ${arch}`); ``` ## `process.argv` \* Type: {string\[]} The `process.argv` property returns an array containing the command-line arguments passed when the Node.js process was launched. The first element will be [`process.execPath`][]. See `process.argv0` if access to the original value of `argv[0]` is needed. If a [program entry point][] was provided, the second element will be the absolute path to it. The remaining elements are additional command-line arguments. For example, assuming the following script for `process-args.js`: ```mjs import { argv } from 'node:process'; // print process.argv argv.forEach((val, index) => { console.log(`${index}: ${val}`); }); ``` ```cjs const { argv } = require('node:process'); // print process.argv argv.forEach((val, index) => { console.log(`${index}: ${val}`); }); ``` Launching the Node.js process as: ```bash node process-args.js one two=three four ``` Would generate the output: ```text 0: /usr/local/bin/node 1: /Users/mjr/work/node/process-args.js 2: one 3: two=three 4: four ``` ## `process.argv0` \* Type: {string} The `process.argv0` property stores a read-only copy of the original value of `argv[0]` passed when Node.js starts. ```console $ bash -c 'exec -a customArgv0 ./node' > process.argv[0] '/Volumes/code/external/node/out/Release/node' > process.argv0 'customArgv0' ``` ## `process.availableMemory()` \* Type: {number} Gets the amount of free memory that is still available to the process (in bytes). See [`uv\_get\_available\_memory`][uv\_get\_available\_memory] for more information. ## `process.channel` \* Type: {Object} If the Node.js process was spawned with an IPC channel (see the [Child Process][] documentation), the `process.channel` property is a reference to the IPC channel. If no IPC channel exists, this property is `undefined`. ### `process.channel.ref()` This method makes the IPC channel keep the event loop of the process running if `.unref()` has been called before. Typically, this is managed through the number of `'disconnect'` and `'message'` listeners on the `process` object. However, this method can be used to explicitly request a specific behavior. ### `process.channel.unref()` This method makes | https://github.com/nodejs/node/blob/main//doc/api/process.md | main | nodejs | [
-0.07847682386636734,
0.034796249121427536,
-0.03246524930000305,
0.0182918943464756,
0.13893136382102966,
-0.07023090124130249,
-0.0227335374802351,
0.028584666550159454,
-0.018111201003193855,
0.027712412178516388,
-0.05909347906708717,
0.026428982615470886,
-0.05423895642161369,
-0.0505... | 0.13387 |
the IPC channel keep the event loop of the process running if `.unref()` has been called before. Typically, this is managed through the number of `'disconnect'` and `'message'` listeners on the `process` object. However, this method can be used to explicitly request a specific behavior. ### `process.channel.unref()` This method makes the IPC channel not keep the event loop of the process running, and lets it finish even while the channel is open. Typically, this is managed through the number of `'disconnect'` and `'message'` listeners on the `process` object. However, this method can be used to explicitly request a specific behavior. ## `process.chdir(directory)` \* `directory` {string} The `process.chdir()` method changes the current working directory of the Node.js process or throws an exception if doing so fails (for instance, if the specified `directory` does not exist). ```mjs import { chdir, cwd } from 'node:process'; console.log(`Starting directory: ${cwd()}`); try { chdir('/tmp'); console.log(`New directory: ${cwd()}`); } catch (err) { console.error(`chdir: ${err}`); } ``` ```cjs const { chdir, cwd } = require('node:process'); console.log(`Starting directory: ${cwd()}`); try { chdir('/tmp'); console.log(`New directory: ${cwd()}`); } catch (err) { console.error(`chdir: ${err}`); } ``` This feature is not available in [`Worker`][] threads. ## `process.config` \* Type: {Object} The `process.config` property returns a frozen `Object` containing the JavaScript representation of the configure options used to compile the current Node.js executable. This is the same as the `config.gypi` file that was produced when running the `./configure` script. An example of the possible output looks like: ```js { target\_defaults: { cflags: [], default\_configuration: 'Release', defines: [], include\_dirs: [], libraries: [] }, variables: { host\_arch: 'x64', napi\_build\_version: 5, node\_install\_npm: 'true', node\_prefix: '', node\_shared\_cares: 'false', node\_shared\_http\_parser: 'false', node\_shared\_libuv: 'false', node\_shared\_zlib: 'false', node\_use\_openssl: 'true', node\_shared\_openssl: 'false', target\_arch: 'x64', v8\_use\_snapshot: 1 } } ``` ## `process.connected` \* Type: {boolean} If the Node.js process is spawned with an IPC channel (see the [Child Process][] and [Cluster][] documentation), the `process.connected` property will return `true` so long as the IPC channel is connected and will return `false` after `process.disconnect()` is called. Once `process.connected` is `false`, it is no longer possible to send messages over the IPC channel using `process.send()`. ## `process.constrainedMemory()` \* Type: {number} Gets the amount of memory available to the process (in bytes) based on limits imposed by the OS. If there is no such constraint, or the constraint is unknown, `0` is returned. See [`uv\_get\_constrained\_memory`][uv\_get\_constrained\_memory] for more information. ## `process.cpuUsage([previousValue])` \* `previousValue` {Object} A previous return value from calling `process.cpuUsage()` \* Returns: {Object} \* `user` {integer} \* `system` {integer} The `process.cpuUsage()` method returns the user and system CPU time usage of the current process, in an object with properties `user` and `system`, whose values are microsecond values (millionth of a second). These values measure time spent in user and system code respectively, and may end up being greater than actual elapsed time if multiple CPU cores are performing work for this process. The result of a previous call to `process.cpuUsage()` can be passed as the argument to the function, to get a diff reading. ```mjs import { cpuUsage } from 'node:process'; const startUsage = cpuUsage(); // { user: 38579, system: 6986 } // spin the CPU for 500 milliseconds const now = Date.now(); while (Date.now() - now < 500); console.log(cpuUsage(startUsage)); // { user: 514883, system: 11226 } ``` ```cjs const { cpuUsage } = require('node:process'); const startUsage = cpuUsage(); // { user: 38579, system: 6986 } // spin the CPU for 500 milliseconds const now = Date.now(); while (Date.now() - now < 500); console.log(cpuUsage(startUsage)); // { user: 514883, system: 11226 } ``` ## `process.cwd()` \* Returns: {string} The `process.cwd()` method returns the current working directory of the | https://github.com/nodejs/node/blob/main//doc/api/process.md | main | nodejs | [
-0.06600836664438248,
-0.054169584065675735,
0.00482753524556756,
0.051881272345781326,
0.09342921525239944,
-0.07307775318622589,
0.052091795951128006,
-0.011930184438824654,
0.12258926779031754,
0.011784500442445278,
-0.04257733002305031,
0.10717344284057617,
-0.07209965586662292,
-0.034... | 0.103527 |
= cpuUsage(); // { user: 38579, system: 6986 } // spin the CPU for 500 milliseconds const now = Date.now(); while (Date.now() - now < 500); console.log(cpuUsage(startUsage)); // { user: 514883, system: 11226 } ``` ## `process.cwd()` \* Returns: {string} The `process.cwd()` method returns the current working directory of the Node.js process. ```mjs import { cwd } from 'node:process'; console.log(`Current directory: ${cwd()}`); ``` ```cjs const { cwd } = require('node:process'); console.log(`Current directory: ${cwd()}`); ``` ## `process.debugPort` \* Type: {number} The port used by the Node.js debugger when enabled. ```mjs import process from 'node:process'; process.debugPort = 5858; ``` ```cjs const process = require('node:process'); process.debugPort = 5858; ``` ## `process.disconnect()` If the Node.js process is spawned with an IPC channel (see the [Child Process][] and [Cluster][] documentation), the `process.disconnect()` method will close the IPC channel to the parent process, allowing the child process to exit gracefully once there are no other connections keeping it alive. The effect of calling `process.disconnect()` is the same as calling [`ChildProcess.disconnect()`][] from the parent process. If the Node.js process was not spawned with an IPC channel, `process.disconnect()` will be `undefined`. ## `process.dlopen(module, filename[, flags])` \* `module` {Object} \* `filename` {string} \* `flags` {os.constants.dlopen} \*\*Default:\*\* `os.constants.dlopen.RTLD\_LAZY` The `process.dlopen()` method allows dynamically loading shared objects. It is primarily used by `require()` to load C++ Addons, and should not be used directly, except in special cases. In other words, [`require()`][] should be preferred over `process.dlopen()` unless there are specific reasons such as custom dlopen flags or loading from ES modules. The `flags` argument is an integer that allows to specify dlopen behavior. See the [`os.constants.dlopen`][] documentation for details. An important requirement when calling `process.dlopen()` is that the `module` instance must be passed. Functions exported by the C++ Addon are then accessible via `module.exports`. The example below shows how to load a C++ Addon, named `local.node`, that exports a `foo` function. All the symbols are loaded before the call returns, by passing the `RTLD\_NOW` constant. In this example the constant is assumed to be available. ```mjs import { dlopen } from 'node:process'; import { constants } from 'node:os'; import { fileURLToPath } from 'node:url'; const module = { exports: {} }; dlopen(module, fileURLToPath(new URL('local.node', import.meta.url)), constants.dlopen.RTLD\_NOW); module.exports.foo(); ``` ```cjs const { dlopen } = require('node:process'); const { constants } = require('node:os'); const { join } = require('node:path'); const module = { exports: {} }; dlopen(module, join(\_\_dirname, 'local.node'), constants.dlopen.RTLD\_NOW); module.exports.foo(); ``` ## `process.emitWarning(warning[, options])` \* `warning` {string|Error} The warning to emit. \* `options` {Object} \* `type` {string} When `warning` is a `String`, `type` is the name to use for the \_type\_ of warning being emitted. \*\*Default:\*\* `'Warning'`. \* `code` {string} A unique identifier for the warning instance being emitted. \* `ctor` {Function} When `warning` is a `String`, `ctor` is an optional function used to limit the generated stack trace. \*\*Default:\*\* `process.emitWarning`. \* `detail` {string} Additional text to include with the error. The `process.emitWarning()` method can be used to emit custom or application specific process warnings. These can be listened for by adding a handler to the [`'warning'`][process\_warning] event. ```mjs import { emitWarning } from 'node:process'; // Emit a warning with a code and additional detail. emitWarning('Something happened!', { code: 'MY\_WARNING', detail: 'This is some additional information', }); // Emits: // (node:56338) [MY\_WARNING] Warning: Something happened! // This is some additional information ``` ```cjs const { emitWarning } = require('node:process'); // Emit a warning with a code and additional detail. emitWarning('Something happened!', { code: 'MY\_WARNING', detail: 'This is some additional information', }); // Emits: // (node:56338) [MY\_WARNING] Warning: Something happened! // This is some additional information ``` In this example, an `Error` object | https://github.com/nodejs/node/blob/main//doc/api/process.md | main | nodejs | [
-0.060109395533800125,
-0.000721729826182127,
-0.027086356654763222,
-0.0020604608580470085,
0.03838706761598587,
-0.09063032269477844,
-0.05297071859240532,
0.09210630506277084,
0.02496916428208351,
0.04107049107551575,
-0.00010429206304252148,
0.03901837766170502,
-0.05793214589357376,
-... | 0.112918 |
```cjs const { emitWarning } = require('node:process'); // Emit a warning with a code and additional detail. emitWarning('Something happened!', { code: 'MY\_WARNING', detail: 'This is some additional information', }); // Emits: // (node:56338) [MY\_WARNING] Warning: Something happened! // This is some additional information ``` In this example, an `Error` object is generated internally by `process.emitWarning()` and passed through to the [`'warning'`][process\_warning] handler. ```mjs import process from 'node:process'; process.on('warning', (warning) => { console.warn(warning.name); // 'Warning' console.warn(warning.message); // 'Something happened!' console.warn(warning.code); // 'MY\_WARNING' console.warn(warning.stack); // Stack trace console.warn(warning.detail); // 'This is some additional information' }); ``` ```cjs const process = require('node:process'); process.on('warning', (warning) => { console.warn(warning.name); // 'Warning' console.warn(warning.message); // 'Something happened!' console.warn(warning.code); // 'MY\_WARNING' console.warn(warning.stack); // Stack trace console.warn(warning.detail); // 'This is some additional information' }); ``` If `warning` is passed as an `Error` object, the `options` argument is ignored. ## `process.emitWarning(warning[, type[, code]][, ctor])` \* `warning` {string|Error} The warning to emit. \* `type` {string} When `warning` is a `String`, `type` is the name to use for the \_type\_ of warning being emitted. \*\*Default:\*\* `'Warning'`. \* `code` {string} A unique identifier for the warning instance being emitted. \* `ctor` {Function} When `warning` is a `String`, `ctor` is an optional function used to limit the generated stack trace. \*\*Default:\*\* `process.emitWarning`. The `process.emitWarning()` method can be used to emit custom or application specific process warnings. These can be listened for by adding a handler to the [`'warning'`][process\_warning] event. ```mjs import { emitWarning } from 'node:process'; // Emit a warning using a string. emitWarning('Something happened!'); // Emits: (node: 56338) Warning: Something happened! ``` ```cjs const { emitWarning } = require('node:process'); // Emit a warning using a string. emitWarning('Something happened!'); // Emits: (node: 56338) Warning: Something happened! ``` ```mjs import { emitWarning } from 'node:process'; // Emit a warning using a string and a type. emitWarning('Something Happened!', 'CustomWarning'); // Emits: (node:56338) CustomWarning: Something Happened! ``` ```cjs const { emitWarning } = require('node:process'); // Emit a warning using a string and a type. emitWarning('Something Happened!', 'CustomWarning'); // Emits: (node:56338) CustomWarning: Something Happened! ``` ```mjs import { emitWarning } from 'node:process'; emitWarning('Something happened!', 'CustomWarning', 'WARN001'); // Emits: (node:56338) [WARN001] CustomWarning: Something happened! ``` ```cjs const { emitWarning } = require('node:process'); process.emitWarning('Something happened!', 'CustomWarning', 'WARN001'); // Emits: (node:56338) [WARN001] CustomWarning: Something happened! ``` In each of the previous examples, an `Error` object is generated internally by `process.emitWarning()` and passed through to the [`'warning'`][process\_warning] handler. ```mjs import process from 'node:process'; process.on('warning', (warning) => { console.warn(warning.name); console.warn(warning.message); console.warn(warning.code); console.warn(warning.stack); }); ``` ```cjs const process = require('node:process'); process.on('warning', (warning) => { console.warn(warning.name); console.warn(warning.message); console.warn(warning.code); console.warn(warning.stack); }); ``` If `warning` is passed as an `Error` object, it will be passed through to the `'warning'` event handler unmodified (and the optional `type`, `code` and `ctor` arguments will be ignored): ```mjs import { emitWarning } from 'node:process'; // Emit a warning using an Error object. const myWarning = new Error('Something happened!'); // Use the Error name property to specify the type name myWarning.name = 'CustomWarning'; myWarning.code = 'WARN001'; emitWarning(myWarning); // Emits: (node:56338) [WARN001] CustomWarning: Something happened! ``` ```cjs const { emitWarning } = require('node:process'); // Emit a warning using an Error object. const myWarning = new Error('Something happened!'); // Use the Error name property to specify the type name myWarning.name = 'CustomWarning'; myWarning.code = 'WARN001'; emitWarning(myWarning); // Emits: (node:56338) [WARN001] CustomWarning: Something happened! ``` A `TypeError` is thrown if `warning` is anything other than a string or `Error` object. While process warnings use `Error` objects, the process warning mechanism is \*\*not\*\* a replacement for normal error handling mechanisms. The following additional handling is implemented if the warning `type` is `'DeprecationWarning'`: \* If the `--throw-deprecation` | https://github.com/nodejs/node/blob/main//doc/api/process.md | main | nodejs | [
-0.012732906267046928,
0.04413650929927826,
0.005149614531546831,
0.08371984213590622,
0.11528889089822769,
-0.05891192704439163,
0.07055170089006424,
0.07718208432197571,
0.08793966472148895,
-0.009428713470697403,
-0.023345738649368286,
-0.052162665873765945,
0.005122098606079817,
-0.036... | 0.232767 |
A `TypeError` is thrown if `warning` is anything other than a string or `Error` object. While process warnings use `Error` objects, the process warning mechanism is \*\*not\*\* a replacement for normal error handling mechanisms. The following additional handling is implemented if the warning `type` is `'DeprecationWarning'`: \* If the `--throw-deprecation` command-line flag is used, the deprecation warning is thrown as an exception rather than being emitted as an event. \* If the `--no-deprecation` command-line flag is used, the deprecation warning is suppressed. \* If the `--trace-deprecation` command-line flag is used, the deprecation warning is printed to `stderr` along with the full stack trace. ### Avoiding duplicate warnings As a best practice, warnings should be emitted only once per process. To do so, place the `emitWarning()` behind a boolean. ```mjs import { emitWarning } from 'node:process'; function emitMyWarning() { if (!emitMyWarning.warned) { emitMyWarning.warned = true; emitWarning('Only warn once!'); } } emitMyWarning(); // Emits: (node: 56339) Warning: Only warn once! emitMyWarning(); // Emits nothing ``` ```cjs const { emitWarning } = require('node:process'); function emitMyWarning() { if (!emitMyWarning.warned) { emitMyWarning.warned = true; emitWarning('Only warn once!'); } } emitMyWarning(); // Emits: (node: 56339) Warning: Only warn once! emitMyWarning(); // Emits nothing ``` ## `process.env` \* Type: {Object} The `process.env` property returns an object containing the user environment. See environ(7). An example of this object looks like: ```js { TERM: 'xterm-256color', SHELL: '/usr/local/bin/bash', USER: 'maciej', PATH: '~/.bin/:/usr/bin:/bin:/usr/sbin:/sbin:/usr/local/bin', PWD: '/Users/maciej', EDITOR: 'vim', SHLVL: '1', HOME: '/Users/maciej', LOGNAME: 'maciej', \_: '/usr/local/bin/node' } ``` It is possible to modify this object, but such modifications will not be reflected outside the Node.js process, or (unless explicitly requested) to other [`Worker`][] threads. In other words, the following example would not work: ```bash node -e 'process.env.foo = "bar"' && echo $foo ``` While the following will: ```mjs import { env } from 'node:process'; env.foo = 'bar'; console.log(env.foo); ``` ```cjs const { env } = require('node:process'); env.foo = 'bar'; console.log(env.foo); ``` Assigning a property on `process.env` will implicitly convert the value to a string. \*\*This behavior is deprecated.\*\* Future versions of Node.js may throw an error when the value is not a string, number, or boolean. ```mjs import { env } from 'node:process'; env.test = null; console.log(env.test); // => 'null' env.test = undefined; console.log(env.test); // => 'undefined' ``` ```cjs const { env } = require('node:process'); env.test = null; console.log(env.test); // => 'null' env.test = undefined; console.log(env.test); // => 'undefined' ``` Use `delete` to delete a property from `process.env`. ```mjs import { env } from 'node:process'; env.TEST = 1; delete env.TEST; console.log(env.TEST); // => undefined ``` ```cjs const { env } = require('node:process'); env.TEST = 1; delete env.TEST; console.log(env.TEST); // => undefined ``` On Windows operating systems, environment variables are case-insensitive. ```mjs import { env } from 'node:process'; env.TEST = 1; console.log(env.test); // => 1 ``` ```cjs const { env } = require('node:process'); env.TEST = 1; console.log(env.test); // => 1 ``` Unless explicitly specified when creating a [`Worker`][] instance, each [`Worker`][] thread has its own copy of `process.env`, based on its parent thread's `process.env`, or whatever was specified as the `env` option to the [`Worker`][] constructor. Changes to `process.env` will not be visible across [`Worker`][] threads, and only the main thread can make changes that are visible to the operating system or to native add-ons. On Windows, a copy of `process.env` on a [`Worker`][] instance operates in a case-sensitive manner unlike the main thread. ## `process.execArgv` \* Type: {string\[]} The `process.execArgv` property returns the set of Node.js-specific command-line options passed when the Node.js process was launched. These options do not appear in the array returned by the [`process.argv`][] property, and do not include | https://github.com/nodejs/node/blob/main//doc/api/process.md | main | nodejs | [
-0.021394431591033936,
0.030045274645090103,
0.033604808151721954,
0.0856277272105217,
0.08046846091747284,
-0.08017710596323013,
0.035259366035461426,
0.06416110694408417,
0.02210049331188202,
-0.006085890345275402,
-0.008075429126620293,
-0.01698184758424759,
0.017839012667536736,
-0.022... | 0.120842 |
[`Worker`][] instance operates in a case-sensitive manner unlike the main thread. ## `process.execArgv` \* Type: {string\[]} The `process.execArgv` property returns the set of Node.js-specific command-line options passed when the Node.js process was launched. These options do not appear in the array returned by the [`process.argv`][] property, and do not include the Node.js executable, the name of the script, or any options following the script name. These options are useful in order to spawn child processes with the same execution environment as the parent. ```bash node --icu-data-dir=./foo --require ./bar.js script.js --version ``` Results in `process.execArgv`: ```json ["--icu-data-dir=./foo", "--require", "./bar.js"] ``` And `process.argv`: ```js ['/usr/local/bin/node', 'script.js', '--version'] ``` Refer to [`Worker` constructor][] for the detailed behavior of worker threads with this property. ## `process.execPath` \* Type: {string} The `process.execPath` property returns the absolute pathname of the executable that started the Node.js process. Symbolic links, if any, are resolved. ```js '/usr/local/bin/node' ``` ## `process.execve(file[, args[, env]])` > Stability: 1 - Experimental \* `file` {string} The name or path of the executable file to run. \* `args` {string\[]} List of string arguments. No argument can contain a null-byte (`\u0000`). \* `env` {Object} Environment key-value pairs. No key or value can contain a null-byte (`\u0000`). \*\*Default:\*\* `process.env`. Replaces the current process with a new process. This is achieved by using the `execve` POSIX function and therefore no memory or other resources from the current process are preserved, except for the standard input, standard output and standard error file descriptor. All other resources are discarded by the system when the processes are swapped, without triggering any exit or close events and without running any cleanup handler. This function will never return, unless an error occurred. This function is not available on Windows or IBM i. ## `process.exit([code])` \* `code` {integer|string|null|undefined} The exit code. For string type, only integer strings (e.g.,'1') are allowed. \*\*Default:\*\* `0`. The `process.exit()` method instructs Node.js to terminate the process synchronously with an exit status of `code`. If `code` is omitted, exit uses either the 'success' code `0` or the value of `process.exitCode` if it has been set. Node.js will not terminate until all the [`'exit'`][] event listeners are called. To exit with a 'failure' code: ```mjs import { exit } from 'node:process'; exit(1); ``` ```cjs const { exit } = require('node:process'); exit(1); ``` The shell that executed Node.js should see the exit code as `1`. Calling `process.exit()` will force the process to exit as quickly as possible even if there are still asynchronous operations pending that have not yet completed fully, including I/O operations to `process.stdout` and `process.stderr`. In most situations, it is not actually necessary to call `process.exit()` explicitly. The Node.js process will exit on its own \_if there is no additional work pending\_ in the event loop. The `process.exitCode` property can be set to tell the process which exit code to use when the process exits gracefully. For instance, the following example illustrates a \_misuse\_ of the `process.exit()` method that could lead to data printed to stdout being truncated and lost: ```mjs import { exit } from 'node:process'; // This is an example of what \*not\* to do: if (someConditionNotMet()) { printUsageToStdout(); exit(1); } ``` ```cjs const { exit } = require('node:process'); // This is an example of what \*not\* to do: if (someConditionNotMet()) { printUsageToStdout(); exit(1); } ``` The reason this is problematic is because writes to `process.stdout` in Node.js are sometimes \_asynchronous\_ and may occur over multiple ticks of the Node.js event loop. Calling `process.exit()`, however, forces the process to exit \_before\_ those additional writes to `stdout` can be performed. Rather than calling `process.exit()` directly, the code \_should\_ | https://github.com/nodejs/node/blob/main//doc/api/process.md | main | nodejs | [
-0.04129514843225479,
0.025614045560359955,
-0.05459245294332504,
0.024828016757965088,
0.05657888948917389,
-0.0770806148648262,
0.014533966779708862,
0.04176513850688934,
0.023037763312458992,
0.0091217877343297,
-0.04518071189522743,
0.041561998426914215,
-0.0473928228020668,
0.01605171... | 0.123153 |
reason this is problematic is because writes to `process.stdout` in Node.js are sometimes \_asynchronous\_ and may occur over multiple ticks of the Node.js event loop. Calling `process.exit()`, however, forces the process to exit \_before\_ those additional writes to `stdout` can be performed. Rather than calling `process.exit()` directly, the code \_should\_ set the `process.exitCode` and allow the process to exit naturally by avoiding scheduling any additional work for the event loop: ```mjs import process from 'node:process'; // How to properly set the exit code while letting // the process exit gracefully. if (someConditionNotMet()) { printUsageToStdout(); process.exitCode = 1; } ``` ```cjs const process = require('node:process'); // How to properly set the exit code while letting // the process exit gracefully. if (someConditionNotMet()) { printUsageToStdout(); process.exitCode = 1; } ``` If it is necessary to terminate the Node.js process due to an error condition, throwing an \_uncaught\_ error and allowing the process to terminate accordingly is safer than calling `process.exit()`. In [`Worker`][] threads, this function stops the current thread rather than the current process. ## `process.exitCode` \* Type: {integer|string|null|undefined} The exit code. For string type, only integer strings (e.g.,'1') are allowed. \*\*Default:\*\* `undefined`. A number which will be the process exit code, when the process either exits gracefully, or is exited via [`process.exit()`][] without specifying a code. The value of `process.exitCode` can be updated by either assigning a value to `process.exitCode` or by passing an argument to [`process.exit()`][]: ```console $ node -e 'process.exitCode = 9'; echo $? 9 $ node -e 'process.exit(42)'; echo $? 42 $ node -e 'process.exitCode = 9; process.exit(42)'; echo $? 42 ``` The value can also be set implicitly by Node.js when unrecoverable errors occur (e.g. such as the encountering of an unsettled top-level await). However explicit manipulations of the exit code always take precedence over implicit ones: ```console $ node --input-type=module -e 'await new Promise(() => {})'; echo $? 13 $ node --input-type=module -e 'process.exitCode = 9; await new Promise(() => {})'; echo $? 9 ``` ## `process.features.cached\_builtins` \* Type: {boolean} A boolean value that is `true` if the current Node.js build is caching builtin modules. ## `process.features.debug` \* Type: {boolean} A boolean value that is `true` if the current Node.js build is a debug build. ## `process.features.inspector` \* Type: {boolean} A boolean value that is `true` if the current Node.js build includes the inspector. ## `process.features.ipv6` > Stability: 0 - Deprecated. This property is always true, and any checks based on it are > redundant. \* Type: {boolean} A boolean value that is `true` if the current Node.js build includes support for IPv6. Since all Node.js builds have IPv6 support, this value is always `true`. ## `process.features.require\_module` \* Type: {boolean} A boolean value that is `true` if the current Node.js build supports [loading ECMAScript modules using `require()`][]. ## `process.features.tls` \* Type: {boolean} A boolean value that is `true` if the current Node.js build includes support for TLS. ## `process.features.tls\_alpn` > Stability: 0 - Deprecated. Use `process.features.tls` instead. \* Type: {boolean} A boolean value that is `true` if the current Node.js build includes support for ALPN in TLS. In Node.js 11.0.0 and later versions, the OpenSSL dependencies feature unconditional ALPN support. This value is therefore identical to that of `process.features.tls`. ## `process.features.tls\_ocsp` > Stability: 0 - Deprecated. Use `process.features.tls` instead. \* Type: {boolean} A boolean value that is `true` if the current Node.js build includes support for OCSP in TLS. In Node.js 11.0.0 and later versions, the OpenSSL dependencies feature unconditional OCSP support. This value is therefore identical to that of `process.features.tls`. ## `process.features.tls\_sni` > Stability: 0 - Deprecated. Use `process.features.tls` instead. \* Type: {boolean} A boolean | https://github.com/nodejs/node/blob/main//doc/api/process.md | main | nodejs | [
-0.008974486030638218,
0.03348613902926445,
0.04714449122548103,
0.06117663532495499,
0.030733469873666763,
-0.026166358962655067,
-0.043231453746557236,
0.08874472975730896,
0.05540155991911888,
0.03713222220540047,
-0.08845703303813934,
-0.011109588667750359,
-0.0004158879746682942,
-0.0... | 0.019198 |
is `true` if the current Node.js build includes support for OCSP in TLS. In Node.js 11.0.0 and later versions, the OpenSSL dependencies feature unconditional OCSP support. This value is therefore identical to that of `process.features.tls`. ## `process.features.tls\_sni` > Stability: 0 - Deprecated. Use `process.features.tls` instead. \* Type: {boolean} A boolean value that is `true` if the current Node.js build includes support for SNI in TLS. In Node.js 11.0.0 and later versions, the OpenSSL dependencies feature unconditional SNI support. This value is therefore identical to that of `process.features.tls`. ## `process.features.typescript` > Stability: 1.2 - Release candidate \* Type: {boolean|string} A value that is `"strip"` by default, `"transform"` if Node.js is run with `--experimental-transform-types`, and `false` if Node.js is run with `--no-strip-types`. ## `process.features.uv` > Stability: 0 - Deprecated. This property is always true, and any checks based on it are > redundant. \* Type: {boolean} A boolean value that is `true` if the current Node.js build includes support for libuv. Since it's not possible to build Node.js without libuv, this value is always `true`. ## `process.finalization.register(ref, callback)` > Stability: 1.1 - Active Development \* `ref` {Object | Function} The reference to the resource that is being tracked. \* `callback` {Function} The callback function to be called when the resource is finalized. \* `ref` {Object | Function} The reference to the resource that is being tracked. \* `event` {string} The event that triggered the finalization. Defaults to 'exit'. This function registers a callback to be called when the process emits the `exit` event if the `ref` object was not garbage collected. If the object `ref` was garbage collected before the `exit` event is emitted, the callback will be removed from the finalization registry, and it will not be called on process exit. Inside the callback you can release the resources allocated by the `ref` object. Be aware that all limitations applied to the `beforeExit` event are also applied to the `callback` function, this means that there is a possibility that the callback will not be called under special circumstances. The idea of this function is to help you free up resources when the starts process exiting, but also let the object be garbage collected if it is no longer being used. Eg: you can register an object that contains a buffer, you want to make sure that buffer is released when the process exit, but if the object is garbage collected before the process exit, we no longer need to release the buffer, so in this case we just remove the callback from the finalization registry. ```cjs const { finalization } = require('node:process'); // Please make sure that the function passed to finalization.register() // does not create a closure around unnecessary objects. function onFinalize(obj, event) { // You can do whatever you want with the object obj.dispose(); } function setup() { // This object can be safely garbage collected, // and the resulting shutdown function will not be called. // There are no leaks. const myDisposableObject = { dispose() { // Free your resources synchronously }, }; finalization.register(myDisposableObject, onFinalize); } setup(); ``` ```mjs import { finalization } from 'node:process'; // Please make sure that the function passed to finalization.register() // does not create a closure around unnecessary objects. function onFinalize(obj, event) { // You can do whatever you want with the object obj.dispose(); } function setup() { // This object can be safely garbage collected, // and the resulting shutdown function will not be called. // There are no leaks. const myDisposableObject = { dispose() { // Free your resources synchronously }, }; finalization.register(myDisposableObject, onFinalize); } setup(); ``` The code above relies | https://github.com/nodejs/node/blob/main//doc/api/process.md | main | nodejs | [
-0.10391220450401306,
0.0733092650771141,
0.01014619879424572,
0.04739919304847717,
0.1140855923295021,
-0.05727415159344673,
-0.018781177699565887,
0.005111068487167358,
0.06602072715759277,
-0.009302695281803608,
-0.08448631316423416,
0.057344336062669754,
-0.04264416918158531,
0.0261457... | -0.021115 |
obj.dispose(); } function setup() { // This object can be safely garbage collected, // and the resulting shutdown function will not be called. // There are no leaks. const myDisposableObject = { dispose() { // Free your resources synchronously }, }; finalization.register(myDisposableObject, onFinalize); } setup(); ``` The code above relies on the following assumptions: \* arrow functions are avoided \* regular functions are recommended to be within the global context (root) Regular functions \_could\_ reference the context where the `obj` lives, making the `obj` not garbage collectible. Arrow functions will hold the previous context. Consider, for example: ```js class Test { constructor() { finalization.register(this, (ref) => ref.dispose()); // Even something like this is highly discouraged // finalization.register(this, () => this.dispose()); } dispose() {} } ``` It is very unlikely (not impossible) that this object will be garbage collected, but if it is not, `dispose` will be called when `process.exit` is called. Be careful and avoid relying on this feature for the disposal of critical resources, as it is not guaranteed that the callback will be called under all circumstances. ## `process.finalization.registerBeforeExit(ref, callback)` > Stability: 1.1 - Active Development \* `ref` {Object | Function} The reference to the resource that is being tracked. \* `callback` {Function} The callback function to be called when the resource is finalized. \* `ref` {Object | Function} The reference to the resource that is being tracked. \* `event` {string} The event that triggered the finalization. Defaults to 'beforeExit'. This function behaves exactly like the `register`, except that the callback will be called when the process emits the `beforeExit` event if `ref` object was not garbage collected. Be aware that all limitations applied to the `beforeExit` event are also applied to the `callback` function, this means that there is a possibility that the callback will not be called under special circumstances. ## `process.finalization.unregister(ref)` > Stability: 1.1 - Active Development \* `ref` {Object | Function} The reference to the resource that was registered previously. This function remove the register of the object from the finalization registry, so the callback will not be called anymore. ```cjs const { finalization } = require('node:process'); // Please make sure that the function passed to finalization.register() // does not create a closure around unnecessary objects. function onFinalize(obj, event) { // You can do whatever you want with the object obj.dispose(); } function setup() { // This object can be safely garbage collected, // and the resulting shutdown function will not be called. // There are no leaks. const myDisposableObject = { dispose() { // Free your resources synchronously }, }; finalization.register(myDisposableObject, onFinalize); // Do something myDisposableObject.dispose(); finalization.unregister(myDisposableObject); } setup(); ``` ```mjs import { finalization } from 'node:process'; // Please make sure that the function passed to finalization.register() // does not create a closure around unnecessary objects. function onFinalize(obj, event) { // You can do whatever you want with the object obj.dispose(); } function setup() { // This object can be safely garbage collected, // and the resulting shutdown function will not be called. // There are no leaks. const myDisposableObject = { dispose() { // Free your resources synchronously }, }; // Please make sure that the function passed to finalization.register() // does not create a closure around unnecessary objects. function onFinalize(obj, event) { // You can do whatever you want with the object obj.dispose(); } finalization.register(myDisposableObject, onFinalize); // Do something myDisposableObject.dispose(); finalization.unregister(myDisposableObject); } setup(); ``` ## `process.getActiveResourcesInfo()` \* Returns: {string\[]} The `process.getActiveResourcesInfo()` method returns an array of strings containing the types of the active resources that are currently keeping the event loop alive. ```mjs import { getActiveResourcesInfo } from 'node:process'; import { | https://github.com/nodejs/node/blob/main//doc/api/process.md | main | nodejs | [
-0.043612707406282425,
0.051627207547426224,
0.014893928542733192,
0.06873267889022827,
0.007184687536209822,
-0.059014998376369476,
0.05659386143088341,
0.05018699914216995,
0.04265517741441727,
-0.005152896977961063,
-0.026736577972769737,
0.09204193204641342,
-0.03890543058514595,
0.002... | 0.158086 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.