text
stringlengths 2
4k
|
---|
import { Argv } from ".";
export = Yargs;
declare function Yargs(
processArgs?: readonly string[] | string,
cwd?: string,
parentRequire?: NodeRequire,
): Argv;
|
import * as Parser from "yargs-parser";
export function applyExtends(config: Record<string, any>, cwd: string, mergeExtends: boolean): Record<string, any>;
export function hideBin(argv: string[]): string[];
export { Parser };
|
// The following TSLint rules have been disabled:
// unified-signatures: Because there is useful information in the argument names of the overloaded signatures
// Convention:
// Use 'union types' when:
// - parameter types have similar signature type (i.e. 'string | ReadonlyArray<string>')
// - parameter names have the same semantic meaning (i.e. ['command', 'commands'] , ['key', 'keys'])
// An example for not using 'union types' is the declaration of 'env' where `prefix` and `enable` parameters
// have different semantics. On the other hand, in the declaration of 'usage', a `command: string` parameter
// has the same semantic meaning with declaring an overload method by using `commands: ReadonlyArray<string>`,
// thus it's preferred to use `command: string | ReadonlyArray<string>`
// Use parameterless declaration instead of declaring all parameters optional,
// when all parameters are optional and more than one
import { Configuration, DetailedArguments } from "yargs-parser";
declare namespace yargs {
type BuilderCallback<T, R> =
| ((args: Argv<T>) => PromiseLike<Argv<R>>)
| ((args: Argv<T>) => Argv<R>)
| ((args: Argv<T>) => void);
type ParserConfigurationOptions = Configuration & {
/** Sort commands alphabetically. Default is `false` */
"sort-commands": boolean;
};
/**
* The type parameter `T` is the expected shape of the parsed options.
* `Arguments<T>` is those options plus `_` and `$0`, and an indexer falling
* back to `unknown` for unknown options.
*
* For the return type / `argv` property, we create a mapped type over
* `Arguments<T>` to simplify the inferred type signature in client code.
*/
interface Argv<T = {}> {
(args?: readonly string[] | string, cwd?: string): Argv<T>;
/**
* Set key names as equivalent such that updates to a key will propagate to aliases and vice-versa.
*
* Optionally `.alias()` can take an object that maps keys to aliases.
* Each key of this object should be the canonical version of the option, and each value should be a string or an array of strings.
*/
// Aliases for previously declared options can inherit the types of those options.
alias<K1 extends keyof T, K2 extends string>(
shortName: K1,
longName: K2 | readonly K2[],
): Argv<T & { [key in K2]: T[K1] }>;
alias<K1 extends keyof T, K2 extends string>(
shortName: K2,
longName: K1 | readonly K1[],
): Argv<T & { [key in K2]: T[K1] }>;
alias(shortName: string | readonly string[], longName: string | readonly string[]): Argv<T>;
alias(aliases: { [shortName: string]: string | readonly string[] }): Argv<T>;
/**
* Get the arguments as a plain old object.
*
* Arguments without a corresponding flag show up in the `argv._` array.
*
* The script name or node command is available at `argv.$0` similarly to how `$0` works in bash or perl.
*
* If `yargs` is executed in an environment that embeds node and there's no script name (e.g. Electron or nw.js),
* it will ignore the first parameter since it expects it to be the script name. In order to override
* this behavior, use `.parse(process.argv.slice(1))` instead of .argv and the first parameter won't be ignored.
*/
argv:
| { [key in keyof Arguments<T> as key | CamelCaseKey<key>]: Arguments<T>[key] }
| Promise<{ [key in keyof Arguments<T> as key | CamelCaseKey<key>]: Arguments<T>[key] }>;
/**
* Tell the parser to interpret `key` as an array.
* If `.array('foo')` is set, `--foo foo bar` will be parsed as `['foo', 'bar']` rather than as `'foo'`.
* Also, if you use the option multiple times all the values will be flattened in one array so `--foo foo --foo bar` will be parsed |
as `['foo', 'bar']`
*
* When the option is used with a positional, use `--` to tell `yargs` to stop adding values to the array.
*/
array<K extends keyof T>(key: K | readonly K[]): Argv<Omit<T, K> & { [key in K]: ToArray<T[key]> }>;
array<K extends string>(
key: K | readonly K[],
): Argv<T & { [key in K]: Array<string | number> | undefined }>;
/**
* Interpret `key` as a boolean. If a non-flag option follows `key` in `process.argv`, that string won't get set as the value of `key`.
*
* `key` will default to `false`, unless a `default(key, undefined)` is explicitly set.
*
* If `key` is an array, interpret all the elements as booleans.
*/
boolean<K extends keyof T>(key: K | readonly K[]): Argv<Omit<T, K> & { [key in K]: boolean | undefined }>;
boolean<K extends string>(key: K | readonly K[]): Argv<T & { [key in K]: boolean | undefined }>;
/**
* Check that certain conditions are met in the provided arguments.
* @param func Called with two arguments, the parsed `argv` hash and an array of options and their aliases.
* If `func` throws or returns a non-truthy value, show the thrown error, usage information, and exit.
* @param global Indicates whether `check()` should be enabled both at the top-level and for each sub-command.
*/
check(func: (argv: Arguments<T>, aliases: { [alias: string]: string }) => any, global?: boolean): Argv<T>;
/**
* Limit valid values for key to a predefined set of choices, given as an array or as an individual value.
* If this method is called multiple times, all enumerated values will be merged together.
* Choices are generally strings or numbers, and value matching is case-sensitive.
*
* Optionally `.choices()` can take an object that maps multiple keys to their choices.
*
* Choices can also be specified as choices in the object given to `option()`.
*/
choices<K extends keyof T, C extends readonly any[]>(
key: K,
values: C,
): Argv<Omit<T, K> & { [key in K]: C[number] | undefined }>;
choices<K extends string, C extends readonly any[]>(
key: K,
values: C,
): Argv<T & { [key in K]: C[number] | undefined }>;
choices<C extends { [key: string]: readonly any[] }>(
choices: C,
): Argv<Omit<T, keyof C> & { [key in keyof C]: C[key][number] | undefined }>;
/**
* Provide a synchronous function to coerce or transform the value(s) given on the command line for `key`.
*
* The coercion function should accept one argument, representing the parsed value from the command line, and should return a new value or throw an error.
* The returned value will be used as the value for `key` (or one of its aliases) in `argv`.
*
* If the function throws, the error will be treated as a validation failure, delegating to either a custom `.fail()` handler or printing the error message in the console.
*
* Coercion will be applied to a value after all other modifications, such as `.normalize()`.
*
* Optionally `.coerce()` can take an object that maps several keys to their respective coercion function.
*
* You can also map the same function to several keys at one time. Just pass an array of keys as the first argument to `.coerce()`.
*
* If you are using dot-notion or arrays, .e.g., `user.email` and `user.password`, coercion will be applied to the final object that has been parsed
*/
coerce<K extends keyof T, V>(
key: K | readonly K[],
func: (arg: any) => V,
): Argv<Omit<T, K> & { [key in K]: V | undefined }>;
coerce<K extends string, V>(
key: K | readonly K[], |
func: (arg: any) => V,
): Argv<T & { [key in K]: V | undefined }>;
coerce<O extends { [key: string]: (arg: any) => any }>(
opts: O,
): Argv<Omit<T, keyof O> & { [key in keyof O]: ReturnType<O[key]> | undefined }>;
/**
* Define the commands exposed by your application.
* @param command Should be a string representing the command or an array of strings representing the command and its aliases.
* @param description Use to provide a description for each command your application accepts (the values stored in `argv._`).
* Set `description` to false to create a hidden command. Hidden commands don't show up in the help output and aren't available for completion.
* @param [builder] Object to give hints about the options that your command accepts.
* Can also be a function. This function is executed with a yargs instance, and can be used to provide advanced command specific help.
*
* Note that when `void` is returned, the handler `argv` object type will not include command-specific arguments.
* @param [handler] Function, which will be executed with the parsed `argv` object.
*/
command<U = T>(
command: string | readonly string[],
description: string,
builder?: BuilderCallback<T, U>,
handler?: (args: ArgumentsCamelCase<U>) => void | Promise<void>,
middlewares?: Array<MiddlewareFunction<U>>,
deprecated?: boolean | string,
): Argv<T>;
command<O extends { [key: string]: Options }>(
command: string | readonly string[],
description: string,
builder?: O,
handler?: (args: ArgumentsCamelCase<InferredOptionTypes<O>>) => void | Promise<void>,
middlewares?: Array<MiddlewareFunction<O>>,
deprecated?: boolean | string,
): Argv<T>;
command<U = any>( // eslint-disable-line @definitelytyped/no-unnecessary-generics
command: string | readonly string[],
description: string,
module: CommandModule<T, U>,
): Argv<T>;
command<U = T>(
command: string | readonly string[],
showInHelp: false,
builder?: BuilderCallback<T, U>,
handler?: (args: ArgumentsCamelCase<U>) => void | Promise<void>,
middlewares?: Array<MiddlewareFunction<U>>,
deprecated?: boolean | string,
): Argv<T>;
command<O extends { [key: string]: Options }>(
command: string | readonly string[],
showInHelp: false,
builder?: O,
handler?: (args: ArgumentsCamelCase<InferredOptionTypes<O>>) => void | Promise<void>,
): Argv<T>;
command<U = any>( // eslint-disable-line @definitelytyped/no-unnecessary-generics
command: string | readonly string[],
showInHelp: false,
module: CommandModule<T, U>,
): Argv<T>;
// eslint-disable-next-line @definitelytyped/no-unnecessary-generics
command<U = any>(module: CommandModule<T, U>): Argv<T>;
// eslint-disable-next-line @definitelytyped/no-unnecessary-generics
command<U = any>(modules: Array<CommandModule<T, U>>): Argv<T>;
// Advanced API
/** Apply command modules from a directory relative to the module calling this method. */
commandDir(dir: string, opts?: RequireDirectoryOptions): Argv<T>;
/**
* Enable bash/zsh-completion shortcuts for commands and options.
*
* If invoked without parameters, `.completion()` will make completion the command to output the completion script.
*
* @param [cmd] When present in `argv._`, will result in the `.bashrc` or `.zshrc` completion script being outputted.
* To enable bash/zsh completions, concat the generated script to your `.bashrc` or `.bash_profile` (o |
r `.zshrc` for zsh).
* @param [description] Provide a description in your usage instructions for the command that generates the completion scripts.
* @param [func] Rather than relying on yargs' default completion functionality, which shiver me timbers is pretty awesome, you can provide your own completion method.
*/
completion(): Argv<T>;
completion(cmd: string, func?: AsyncCompletionFunction): Argv<T>;
completion(cmd: string, func?: SyncCompletionFunction): Argv<T>;
completion(cmd: string, func?: PromiseCompletionFunction): Argv<T>;
completion(cmd: string, func?: FallbackCompletionFunction): Argv<T>;
completion(cmd: string, description?: string | false, func?: AsyncCompletionFunction): Argv<T>;
completion(cmd: string, description?: string | false, func?: SyncCompletionFunction): Argv<T>;
completion(cmd: string, description?: string | false, func?: PromiseCompletionFunction): Argv<T>;
completion(cmd: string, description?: string | false, func?: FallbackCompletionFunction): Argv<T>;
/**
* Tells the parser that if the option specified by `key` is passed in, it should be interpreted as a path to a JSON config file.
* The file is loaded and parsed, and its properties are set as arguments.
* Because the file is loaded using Node's require(), the filename MUST end in `.json` to be interpreted correctly.
*
* If invoked without parameters, `.config()` will make --config the option to pass the JSON config file.
*
* @param [description] Provided to customize the config (`key`) option in the usage string.
* @param [explicitConfigurationObject] An explicit configuration `object`
*/
config(): Argv<T>;
config(
key: string | readonly string[],
description?: string,
parseFn?: (configPath: string) => object,
): Argv<T>;
config(key: string | readonly string[], parseFn: (configPath: string) => object): Argv<T>;
config(explicitConfigurationObject: object): Argv<T>;
/**
* Given the key `x` is set, the key `y` must not be set. `y` can either be a single string or an array of argument names that `x` conflicts with.
*
* Optionally `.conflicts()` can accept an object specifying multiple conflicting keys.
*/
conflicts(key: string, value: string | readonly string[]): Argv<T>;
conflicts(conflicts: { [key: string]: string | readonly string[] }): Argv<T>;
/**
* Interpret `key` as a boolean flag, but set its parsed value to the number of flag occurrences rather than `true` or `false`. Default value is thus `0`.
*/
count<K extends keyof T>(key: K | readonly K[]): Argv<Omit<T, K> & { [key in K]: number }>;
count<K extends string>(key: K | readonly K[]): Argv<T & { [key in K]: number }>;
/**
* Set `argv[key]` to `value` if no option was specified in `process.argv`.
*
* Optionally `.default()` can take an object that maps keys to default values.
*
* The default value can be a `function` which returns a value. The name of the function will be used in the usage string.
*
* Optionally, `description` can also be provided and will take precedence over displaying the value in the usage instructions.
*/
default<K extends keyof T, V>(key: K, value: V, description?: string): Argv<Omit<T, K> & { [key in K]: V }>;
default<K extends string, V>(key: K, value: V, description?: string): Argv<T & { [key in K]: V }>;
default<D extends { [key: string]: any }>(defaults: D, description?: string): Argv<Omit<T, keyof D> & D>;
/**
* @deprecated since version 6.6.0
* Use '.demandCommand()' or '.demandOption()' instead
*/
demand<K extends keyof T>(key: K | readonly K[], msg?: s |
tring | true): Argv<Defined<T, K>>;
demand<K extends string>(key: K | readonly K[], msg?: string | true): Argv<T & { [key in K]: unknown }>;
demand(key: string | readonly string[], required?: boolean): Argv<T>;
demand(positionals: number, msg: string): Argv<T>;
demand(positionals: number, required?: boolean): Argv<T>;
demand(positionals: number, max: number, msg?: string): Argv<T>;
/**
* @param key If is a string, show the usage information and exit if key wasn't specified in `process.argv`.
* If is an array, demand each element.
* @param msg If string is given, it will be printed when the argument is missing, instead of the standard error message.
* @param demand Controls whether the option is demanded; this is useful when using .options() to specify command line parameters.
*/
demandOption<K extends keyof T>(key: K | readonly K[], msg?: string | true): Argv<Defined<T, K>>;
demandOption<K extends string>(
key: K | readonly K[],
msg?: string | true,
): Argv<T & { [key in K]: unknown }>;
demandOption(key: string | readonly string[], demand?: boolean): Argv<T>;
/**
* Demand in context of commands.
* You can demand a minimum and a maximum number a user can have within your program, as well as provide corresponding error messages if either of the demands is not met.
*/
demandCommand(): Argv<T>;
demandCommand(min: number, minMsg?: string): Argv<T>;
demandCommand(min: number, max?: number, minMsg?: string, maxMsg?: string): Argv<T>;
/**
* Shows a [deprecated] notice in front of the option
*/
deprecateOption(option: string, msg?: string): Argv<T>;
/**
* Describe a `key` for the generated usage information.
*
* Optionally `.describe()` can take an object that maps keys to descriptions.
*/
describe(key: string | readonly string[], description: string): Argv<T>;
describe(descriptions: { [key: string]: string }): Argv<T>;
/** Should yargs attempt to detect the os' locale? Defaults to `true`. */
detectLocale(detect: boolean): Argv<T>;
/**
* Tell yargs to parse environment variables matching the given prefix and apply them to argv as though they were command line arguments.
*
* Use the "__" separator in the environment variable to indicate nested options. (e.g. prefix_nested__foo => nested.foo)
*
* If this method is called with no argument or with an empty string or with true, then all env vars will be applied to argv.
*
* Program arguments are defined in this order of precedence:
* 1. Command line args
* 2. Env vars
* 3. Config file/objects
* 4. Configured defaults
*
* Env var parsing is disabled by default, but you can also explicitly disable it by calling `.env(false)`, e.g. if you need to undo previous configuration.
*/
env(): Argv<T>;
env(prefix: string): Argv<T>;
env(enable: boolean): Argv<T>;
/** A message to print at the end of the usage instructions */
epilog(msg: string): Argv<T>;
/** A message to print at the end of the usage instructions */
epilogue(msg: string): Argv<T>;
/**
* Give some example invocations of your program.
* Inside `cmd`, the string `$0` will get interpolated to the current script name or node command for the present script similar to how `$0` works in bash or perl.
* Examples will be printed out as part of the help message.
*/
example(command: string, description: string): Argv<T>;
example(command: ReadonlyArray<[string, string?]>): Argv<T>;
/** Manually indicate that the program should exit, and provide context about why we wanted to |
exit. Follows the behavior set by `.exitProcess().` */
exit(code: number, err: Error): void;
/**
* By default, yargs exits the process when the user passes a help flag, the user uses the `.version` functionality, validation fails, or the command handler fails.
* Calling `.exitProcess(false)` disables this behavior, enabling further actions after yargs have been validated.
*/
exitProcess(enabled: boolean): Argv<T>;
/**
* Method to execute when a failure occurs, rather than printing the failure message.
* @param func Is called with the failure message that would have been printed, the Error instance originally thrown and yargs state when the failure occurred.
*/
fail(func: ((msg: string, err: Error, yargs: Argv<T>) => any) | boolean): Argv<T>;
/**
* Allows to programmatically get completion choices for any line.
* @param args An array of the words in the command line to complete.
* @param done The callback to be called with the resulting completions.
*/
getCompletion(
args: readonly string[],
done: (err: Error | null, completions: readonly string[]) => void,
): Argv<T>;
getCompletion(args: readonly string[], done?: never): Promise<readonly string[]>;
/**
* Returns a promise which resolves to a string containing the help text.
*/
getHelp(): Promise<string>;
/**
* Indicate that an option (or group of options) should not be reset when a command is executed
*
* Options default to being global.
*/
global(key: string | readonly string[]): Argv<T>;
/** Given a key, or an array of keys, places options under an alternative heading when displaying usage instructions */
group(key: string | readonly string[], groupName: string): Argv<T>;
/** Hides a key from the generated usage information. Unless a `--show-hidden` option is also passed with `--help` (see `showHidden()`). */
hide(key: string): Argv<T>;
/**
* Configure an (e.g. `--help`) and implicit command that displays the usage string and exits the process.
* By default yargs enables help on the `--help` option.
*
* Note that any multi-char aliases (e.g. `help`) used for the help option will also be used for the implicit command.
* If there are no multi-char aliases (e.g. `h`), then all single-char aliases will be used for the command.
*
* If invoked without parameters, `.help()` will use `--help` as the option and help as the implicit command to trigger help output.
*
* @param [description] Customizes the description of the help option in the usage string.
* @param [enableExplicit] If `false` is provided, it will disable --help.
*/
help(): Argv<T>;
help(enableExplicit: boolean): Argv<T>;
help(option: string, enableExplicit: boolean): Argv<T>;
help(option: string, description?: string, enableExplicit?: boolean): Argv<T>;
/**
* Given the key `x` is set, it is required that the key `y` is set.
* y` can either be the name of an argument to imply, a number indicating the position of an argument or an array of multiple implications to associate with `x`.
*
* Optionally `.implies()` can accept an object specifying multiple implications.
*/
implies(key: string, value: string | readonly string[]): Argv<T>;
implies(implies: { [key: string]: string | readonly string[] }): Argv<T>;
/**
* Return the locale that yargs is currently using.
*
* By default, yargs will auto-detect the operating system's locale so that yargs-generated help content will display in the user's language.
*/
locale(): string;
/**
* Override the aut |
o-detected locale from the user's operating system with a static locale.
* Note that the OS locale can be modified by setting/exporting the `LC_ALL` environment variable.
*/
locale(loc: string): Argv<T>;
/**
* Define global middleware functions to be called first, in list order, for all cli command.
* @param callbacks Can be a function or a list of functions. Each callback gets passed a reference to argv.
* @param [applyBeforeValidation] Set to `true` to apply middleware before validation. This will execute the middleware prior to validation checks, but after parsing.
*/
middleware(
callbacks: MiddlewareFunction<T> | ReadonlyArray<MiddlewareFunction<T>>,
applyBeforeValidation?: boolean,
): Argv<T>;
/**
* The number of arguments that should be consumed after a key. This can be a useful hint to prevent parsing ambiguity.
*
* Optionally `.nargs()` can take an object of `key`/`narg` pairs.
*/
nargs(key: string, count: number): Argv<T>;
nargs(nargs: { [key: string]: number }): Argv<T>;
/** The key provided represents a path and should have `path.normalize()` applied. */
normalize<K extends keyof T>(key: K | readonly K[]): Argv<Omit<T, K> & { [key in K]: ToString<T[key]> }>;
normalize<K extends string>(key: K | readonly K[]): Argv<T & { [key in K]: string | undefined }>;
/**
* Tell the parser to always interpret key as a number.
*
* If `key` is an array, all elements will be parsed as numbers.
*
* If the option is given on the command line without a value, `argv` will be populated with `undefined`.
*
* If the value given on the command line cannot be parsed as a number, `argv` will be populated with `NaN`.
*
* Note that decimals, hexadecimals, and scientific notation are all accepted.
*/
number<K extends keyof T>(key: K | readonly K[]): Argv<Omit<T, K> & { [key in K]: ToNumber<T[key]> }>;
number<K extends string>(key: K | readonly K[]): Argv<T & { [key in K]: number | undefined }>;
/**
* Method to execute when a command finishes successfully.
* @param func Is called with the successful result of the command that finished.
*/
onFinishCommand(func: (result: any) => void): Argv<T>;
/**
* This method can be used to make yargs aware of options that could exist.
* You can also pass an opt object which can hold further customization, like `.alias()`, `.demandOption()` etc. for that option.
*/
option<K extends keyof T, O extends Options>(
key: K,
options: O,
): Argv<Omit<T, K> & { [key in K]: InferredOptionType<O> } & Alias<O>>;
option<K extends string, O extends Options>(
key: K,
options: O,
): Argv<T & { [key in K]: InferredOptionType<O> } & Alias<O>>;
option<O extends { [key: string]: Options }>(
options: O,
): Argv<Omit<T, keyof O> & InferredOptionTypes<O> & Alias<O>>;
/**
* This method can be used to make yargs aware of options that could exist.
* You can also pass an opt object which can hold further customization, like `.alias()`, `.demandOption()` etc. for that option.
*/
options<K extends keyof T, O extends Options>(
key: K,
options: O,
): Argv<Omit<T, K> & { [key in K]: InferredOptionType<O> }>;
options<K extends string, O extends Options>(
key: K,
options: O,
): Argv<T & { [key in K]: InferredOptionType<O> }>;
options<O extends { [key: string]: Options }>(options: O): Argv<Omit<T, keyof O> & InferredOptionTypes<O>>;
/**
* Parse `args` instead of `process.argv`. Returns the `argv` object. `args` may e |
ither be a pre-processed argv array, or a raw argument string.
*
* Note: Providing a callback to parse() disables the `exitProcess` setting until after the callback is invoked.
* @param [context] Provides a useful mechanism for passing state information to commands
*/
parse():
| { [key in keyof Arguments<T> as key | CamelCaseKey<key>]: Arguments<T>[key] }
| Promise<{ [key in keyof Arguments<T> as key | CamelCaseKey<key>]: Arguments<T>[key] }>;
parse(
arg: string | readonly string[],
context?: object,
parseCallback?: ParseCallback<T>,
):
| { [key in keyof Arguments<T> as key | CamelCaseKey<key>]: Arguments<T>[key] }
| Promise<{ [key in keyof Arguments<T> as key | CamelCaseKey<key>]: Arguments<T>[key] }>;
parseSync(): { [key in keyof Arguments<T> as key | CamelCaseKey<key>]: Arguments<T>[key] };
parseSync(
arg: string | readonly string[],
context?: object,
parseCallback?: ParseCallback<T>,
): { [key in keyof Arguments<T> as key | CamelCaseKey<key>]: Arguments<T>[key] };
parseAsync(): Promise<{ [key in keyof Arguments<T> as key | CamelCaseKey<key>]: Arguments<T>[key] }>;
parseAsync(
arg: string | readonly string[],
context?: object,
parseCallback?: ParseCallback<T>,
): Promise<{ [key in keyof Arguments<T> as key | CamelCaseKey<key>]: Arguments<T>[key] }>;
/**
* If the arguments have not been parsed, this property is `false`.
*
* If the arguments have been parsed, this contain detailed parsed arguments.
*/
parsed: DetailedArguments | false;
/** Allows to configure advanced yargs features. */
parserConfiguration(configuration: Partial<ParserConfigurationOptions>): Argv<T>;
/**
* Similar to `config()`, indicates that yargs should interpret the object from the specified key in package.json as a configuration object.
* @param [cwd] If provided, the package.json will be read from this location
*/
pkgConf(key: string | readonly string[], cwd?: string): Argv<T>;
/**
* Allows you to configure a command's positional arguments with an API similar to `.option()`.
* `.positional()` should be called in a command's builder function, and is not available on the top-level yargs instance. If so, it will throw an error.
*/
positional<K extends keyof T, O extends PositionalOptions>(
key: K,
opt: O,
): Argv<Omit<T, K> & { [key in K]: InferredOptionType<O> }>;
positional<K extends string, O extends PositionalOptions>(
key: K,
opt: O,
): Argv<T & { [key in K]: InferredOptionType<O> }>;
/** Should yargs provide suggestions regarding similar commands if no matching command is found? */
recommendCommands(): Argv<T>;
/**
* @deprecated since version 6.6.0
* Use '.demandCommand()' or '.demandOption()' instead
*/
require<K extends keyof T>(key: K | readonly K[], msg?: string | true): Argv<Defined<T, K>>;
require(key: string, msg: string): Argv<T>;
require(key: string, required: boolean): Argv<T>;
require(keys: readonly number[], msg: string): Argv<T>;
require(keys: readonly number[], required: boolean): Argv<T>;
require(positionals: number, required: boolean): Argv<T>;
require(positionals: number, msg: string): Argv<T>;
/**
* @deprecated since version 6.6.0
* Use '.demandCommand()' or '.demandOption()' instead
*/
required<K extends keyof T>(key: K | readonly K[], msg?: string | true): Argv<Defined<T, K>>;
required(key: string, msg: string): Argv<T>;
required(key: string, required: boolean): Argv<T>;
|
required(keys: readonly number[], msg: string): Argv<T>;
required(keys: readonly number[], required: boolean): Argv<T>;
required(positionals: number, required: boolean): Argv<T>;
required(positionals: number, msg: string): Argv<T>;
requiresArg(key: string | readonly string[]): Argv<T>;
/** Set the name of your script ($0). Default is the base filename executed by node (`process.argv[1]`) */
scriptName($0: string): Argv<T>;
/**
* Generate a bash completion script.
* Users of your application can install this script in their `.bashrc`, and yargs will provide completion shortcuts for commands and options.
*/
showCompletionScript(): Argv<T>;
/**
* Configure the `--show-hidden` option that displays the hidden keys (see `hide()`).
* @param option If `boolean`, it enables/disables this option altogether. i.e. hidden keys will be permanently hidden if first argument is `false`.
* If `string` it changes the key name ("--show-hidden").
* @param description Changes the default description ("Show hidden options")
*/
showHidden(option?: string | boolean): Argv<T>;
showHidden(option: string, description?: string): Argv<T>;
/**
* Print the usage data using the console function consoleLevel for printing.
* @param [consoleLevel='error']
*/
showHelp(consoleLevel?: string): Argv<T>;
/**
* Provide the usage data as a string.
* @param printCallback a function with a single argument.
*/
showHelp(printCallback: (s: string) => void): Argv<T>;
/**
* By default, yargs outputs a usage string if any error is detected.
* Use the `.showHelpOnFail()` method to customize this behavior.
* @param enable If `false`, the usage string is not output.
* @param [message] Message that is output after the error message.
*/
showHelpOnFail(enable: boolean, message?: string): Argv<T>;
/**
* Print the version data using the console function consoleLevel or the specified function.
* @param [level='error']
*/
showVersion(level?: "error" | "log" | ((message: string) => void)): Argv<T>;
/** Specifies either a single option key (string), or an array of options. If any of the options is present, yargs validation is skipped. */
skipValidation(key: string | readonly string[]): Argv<T>;
/**
* Any command-line argument given that is not demanded, or does not have a corresponding description, will be reported as an error.
*
* Unrecognized commands will also be reported as errors.
*/
strict(): Argv<T>;
strict(enabled: boolean): Argv<T>;
/**
* Similar to .strict(), except that it only applies to unrecognized commands.
* A user can still provide arbitrary options, but unknown positional commands
* will raise an error.
*/
strictCommands(): Argv<T>;
strictCommands(enabled: boolean): Argv<T>;
/**
* Similar to `.strict()`, except that it only applies to unrecognized options. A
* user can still provide arbitrary positional options, but unknown options
* will raise an error.
*/
strictOptions(): Argv<T>;
strictOptions(enabled: boolean): Argv<T>;
/**
* Tell the parser logic not to interpret `key` as a number or boolean. This can be useful if you need to preserve leading zeros in an input.
*
* If `key` is an array, interpret all the elements as strings.
*
* `.string('_')` will result in non-hyphenated arguments being interpreted as strings, regardless of whether they resemble numbers.
*/
string<K extends keyof T>(key: K | readonly K[]): Argv<Omit<T, K> & { [key in K]: ToString< |
T[key]> }>;
string<K extends string>(key: K | readonly K[]): Argv<T & { [key in K]: string | undefined }>;
// Intended to be used with '.wrap()'
terminalWidth(): number;
updateLocale(obj: { [key: string]: string }): Argv<T>;
/**
* Override the default strings used by yargs with the key/value pairs provided in obj
*
* If you explicitly specify a locale(), you should do so before calling `updateStrings()`.
*/
updateStrings(obj: { [key: string]: string }): Argv<T>;
/**
* Set a usage message to show which commands to use.
* Inside `message`, the string `$0` will get interpolated to the current script name or node command for the present script similar to how `$0` works in bash or perl.
*
* If the optional `description`/`builder`/`handler` are provided, `.usage()` acts an an alias for `.command()`.
* This allows you to use `.usage()` to configure the default command that will be run as an entry-point to your application
* and allows you to provide configuration for the positional arguments accepted by your program:
*/
usage(message: string): Argv<T>;
usage<U>(
command: string | readonly string[],
description: string,
builder?: (args: Argv<T>) => Argv<U>,
handler?: (args: ArgumentsCamelCase<U>) => void | Promise<void>,
): Argv<T>;
usage<U>(
command: string | readonly string[],
showInHelp: boolean,
builder?: (args: Argv<T>) => Argv<U>,
handler?: (args: ArgumentsCamelCase<U>) => void | Promise<void>,
): Argv<T>;
usage<O extends { [key: string]: Options }>(
command: string | readonly string[],
description: string,
builder?: O,
handler?: (args: ArgumentsCamelCase<InferredOptionTypes<O>>) => void | Promise<void>,
): Argv<T>;
usage<O extends { [key: string]: Options }>(
command: string | readonly string[],
showInHelp: boolean,
builder?: O,
handler?: (args: ArgumentsCamelCase<InferredOptionTypes<O>>) => void | Promise<void>,
): Argv<T>;
/**
* Add an option (e.g. `--version`) that displays the version number (given by the version parameter) and exits the process.
* By default yargs enables version for the `--version` option.
*
* If no arguments are passed to version (`.version()`), yargs will parse the package.json of your module and use its version value.
*
* If the boolean argument `false` is provided, it will disable `--version`.
*/
version(): Argv<T>;
version(version: string): Argv<T>;
version(enable: boolean): Argv<T>;
version(optionKey: string, version: string): Argv<T>;
version(optionKey: string, description: string, version: string): Argv<T>;
/**
* Format usage output to wrap at columns many columns.
*
* By default wrap will be set to `Math.min(80, windowWidth)`. Use `.wrap(null)` to specify no column limit (no right-align).
* Use `.wrap(yargs.terminalWidth())` to maximize the width of yargs' usage instructions.
*/
wrap(columns: number | null): Argv<T>;
}
type Arguments<T = {}> = T & {
/** Non-option arguments */
_: Array<string | number>;
/** The script name or node command */
$0: string;
/** All remaining options */
[argName: string]: unknown;
};
/** Arguments type, with camelcased keys */
type ArgumentsCamelCase<T = {}> = { [key in keyof T as key | CamelCaseKey<key>]: T[key] } & {
/** Non-option arguments */
_: Array<string | number>;
/** The script name or node command */
$0: string;
/** All remaining options */
[argName: strin |
g]: unknown;
};
interface RequireDirectoryOptions {
/** Look for command modules in all subdirectories and apply them as a flattened (non-hierarchical) list. */
recurse?: boolean | undefined;
/** The types of files to look for when requiring command modules. */
extensions?: readonly string[] | undefined;
/**
* A synchronous function called for each command module encountered.
* Accepts `commandObject`, `pathToFile`, and `filename` as arguments.
* Returns `commandObject` to include the command; any falsy value to exclude/skip it.
*/
visit?: ((commandObject: any, pathToFile?: string, filename?: string) => any) | undefined;
/** Whitelist certain modules */
include?: RegExp | ((pathToFile: string) => boolean) | undefined;
/** Blacklist certain modules. */
exclude?: RegExp | ((pathToFile: string) => boolean) | undefined;
}
interface Options {
/** string or array of strings, alias(es) for the canonical option key, see `alias()` */
alias?: string | readonly string[] | undefined;
/** boolean, interpret option as an array, see `array()` */
array?: boolean | undefined;
/** boolean, interpret option as a boolean flag, see `boolean()` */
boolean?: boolean | undefined;
/** value or array of values, limit valid option arguments to a predefined set, see `choices()` */
choices?: Choices | undefined;
/** function, coerce or transform parsed command line values into another value, see `coerce()` */
coerce?: ((arg: any) => any) | undefined;
/** boolean, interpret option as a path to a JSON config file, see `config()` */
config?: boolean | undefined;
/** function, provide a custom config parsing function, see `config()` */
configParser?: ((configPath: string) => object) | undefined;
/** string or object, require certain keys not to be set, see `conflicts()` */
conflicts?: string | readonly string[] | { [key: string]: string | readonly string[] } | undefined;
/** boolean, interpret option as a count of boolean flags, see `count()` */
count?: boolean | undefined;
/** value, set a default value for the option, see `default()` */
default?: any;
/** string, use this description for the default value in help content, see `default()` */
defaultDescription?: string | undefined;
/**
* @deprecated since version 6.6.0
* Use 'demandOption' instead
*/
demand?: boolean | string | undefined;
/** boolean or string, mark the argument as deprecated, see `deprecateOption()` */
deprecate?: boolean | string | undefined;
/** boolean or string, mark the argument as deprecated, see `deprecateOption()` */
deprecated?: boolean | string | undefined;
/** boolean or string, demand the option be given, with optional error message, see `demandOption()` */
demandOption?: boolean | string | undefined;
/** string, the option description for help content, see `describe()` */
desc?: string | undefined;
/** string, the option description for help content, see `describe()` */
describe?: string | undefined;
/** string, the option description for help content, see `describe()` */
description?: string | undefined;
/** boolean, indicate that this key should not be reset when a command is invoked, see `global()` */
global?: boolean | undefined;
/** string, when displaying usage instructions place the option under an alternative group heading, see `group()` */
group?: string | undefined;
/** don't display option in help output. */
hidden?: boolean | undefined;
/** string or object, require certain keys to be set, see `implies()` */
implies?: string | readonly string[] | { [key: stri |
ng]: string | readonly string[] } | undefined;
/** number, specify how many arguments should be consumed for the option, see `nargs()` */
nargs?: number | undefined;
/** boolean, apply path.normalize() to the option, see `normalize()` */
normalize?: boolean | undefined;
/** boolean, interpret option as a number, `number()` */
number?: boolean | undefined;
/**
* @deprecated since version 6.6.0
* Use 'demandOption' instead
*/
require?: boolean | string | undefined;
/**
* @deprecated since version 6.6.0
* Use 'demandOption' instead
*/
required?: boolean | string | undefined;
/** boolean, require the option be specified with a value, see `requiresArg()` */
requiresArg?: boolean | undefined;
/** boolean, skips validation if the option is present, see `skipValidation()` */
skipValidation?: boolean | undefined;
/** boolean, interpret option as a string, see `string()` */
string?: boolean | undefined;
type?: "array" | "count" | PositionalOptionsType | undefined;
}
interface PositionalOptions {
/** string or array of strings, see `alias()` */
alias?: string | readonly string[] | undefined;
/** boolean, interpret option as an array, see `array()` */
array?: boolean | undefined;
/** value or array of values, limit valid option arguments to a predefined set, see `choices()` */
choices?: Choices | undefined;
/** function, coerce or transform parsed command line values into another value, see `coerce()` */
coerce?: ((arg: any) => any) | undefined;
/** string or object, require certain keys not to be set, see `conflicts()` */
conflicts?: string | readonly string[] | { [key: string]: string | readonly string[] } | undefined;
/** value, set a default value for the option, see `default()` */
default?: any;
/** boolean or string, demand the option be given, with optional error message, see `demandOption()` */
demandOption?: boolean | string | undefined;
/** string, the option description for help content, see `describe()` */
desc?: string | undefined;
/** string, the option description for help content, see `describe()` */
describe?: string | undefined;
/** string, the option description for help content, see `describe()` */
description?: string | undefined;
/** string or object, require certain keys to be set, see `implies()` */
implies?: string | readonly string[] | { [key: string]: string | readonly string[] } | undefined;
/** boolean, apply path.normalize() to the option, see normalize() */
normalize?: boolean | undefined;
type?: PositionalOptionsType | undefined;
}
// not implemented: yargs camelizes '_', but only if there's a '-' in the arg name
// not implemented: yargs decamelizes (converts fooBar to foo-bar)
/** Convert literal string types like 'foo-bar' to 'FooBar' */
type PascalCase<S extends string> = string extends S ? string
: S extends `${infer T}-${infer U}` ? `${Capitalize<T>}${PascalCase<U>}`
: Capitalize<S>;
/** Convert literal string types like 'foo-bar' to 'fooBar' */
type CamelCase<S extends string> = string extends S ? string
: S extends `${infer T}-${infer U}` ? `${T}${PascalCase<U>}`
: S;
/** Convert literal string types like 'foo-bar' to 'fooBar', allowing all `PropertyKey` types */
type CamelCaseKey<K extends PropertyKey> = K extends string ? Exclude<CamelCase<K>, ""> : K;
/** Remove keys K in T */
type Omit<T, K> = { [key in Exclude<keyof T, K>]: T[key] };
/** Remove undefined as a possible value for keys K in T */
type Defined<T, K extends keyof T> = Omit<T, K> & { [key in K]: Exclude<T[key], undefined> };
/** Convert T to T[] |
and T | undefined to T[] | undefined */
type ToArray<T> = Array<Exclude<T, undefined>> | Extract<T, undefined>;
/** Gives string[] if T is an array type, otherwise string. Preserves | undefined. */
type ToString<T> = (Exclude<T, undefined> extends any[] ? string[] : string) | Extract<T, undefined>;
/** Gives number[] if T is an array type, otherwise number. Preserves | undefined. */
type ToNumber<T> = (Exclude<T, undefined> extends any[] ? number[] : number) | Extract<T, undefined>;
// prettier-ignore
type InferredOptionType<O extends Options | PositionalOptions> =
// Handle special cases first
O extends ({ coerce: (arg: any) => infer T }) ? IsRequiredOrHasDefault<O> extends true ? T : T | undefined
: O extends (
| { type: "count"; default: infer D }
| { count: true; default: infer D }
) ? number | Exclude<D, undefined>
: O extends (
| { type: "count" }
| { count: true }
) ? number
// Try to infer type with InferredOptionTypePrimitive
: IsUnknown<InferredOptionTypePrimitive<O>> extends false ? InferredOptionTypePrimitive<O>
// Use the type of `default` as the last resort
: O extends ({ default: infer D }) ? Exclude<D, undefined>
: unknown;
type Alias<O extends Options | PositionalOptions> = O extends { alias: infer T }
? T extends Exclude<string, T> ? { [key in T]: InferredOptionType<O> } : {}
: {};
// prettier-ignore
type IsRequiredOrHasDefault<O extends Options | PositionalOptions> = O extends (
| { required: string | true }
| { require: string | true }
| { demand: string | true }
| { demandOption: string | true }
| { default: {} }
) ? true
: false;
type IsAny<T> = 0 extends (1 & T) ? true : false;
// prettier-ignore
type IsUnknown<T> = IsAny<T> extends true ? false
: unknown extends T ? true
: false;
// prettier-ignore
type InferredOptionTypePrimitive<O extends Options | PositionalOptions> = O extends { default: infer D }
? IsRequiredOrHasDefault<O> extends true ? InferredOptionTypeInner<O> | Exclude<D, undefined>
: InferredOptionTypeInner<O> | D
: IsRequiredOrHasDefault<O> extends true ? InferredOptionTypeInner<O>
: InferredOptionTypeInner<O> | undefined;
// prettier-ignore
type InferredOptionTypeInner<O extends Options | PositionalOptions> = O extends
{ type: "array"; choices: ReadonlyArray<infer C> } ? C[]
: O extends { type: "array"; string: true } ? string[]
: O extends { type: "array"; number: true } ? number[]
: O extends { type: "array"; normalize: true } ? string[]
: O extends { array: true; choices: ReadonlyArray<infer C> } ? C[]
: O extends { array: true; type: "string" } ? string[]
: O extends { array: true; type: "number" } ? number[]
: O extends { array: true; string: true } ? string[]
: O extends { array: true; number: true } ? number[]
: O extends { array: true; normalize: true } ? string[]
: O extends { choices: ReadonlyArray<infer C> } ? C
: O extends { type: "array" } ? Array<string | number>
: O extends { type: "boolean" } ? boolean
: O extends { type: "number" } ? number
: O extends { type: "string" } ? string
: O extends { array: true } ? Array<string | number>
: O extends { boolean: true } ? boolean
: O extends { number: true } ? number
: O extends { string: true } ? string
: O extends { normalize: true } ? string
: unknown;
type InferredOptionTypes<O extends { [key: string]: Options }> = { [key in keyof O]: InferredOptionType<O[key]> };
interface CommandModule<T = {}, U = {}> {
/** array of strings (or a single string) representing aliases of `e |
xports.command`, positional args defined in an alias are ignored */
aliases?: readonly string[] | string | undefined;
/** object declaring the options the command accepts, or a function accepting and returning a yargs instance */
builder?: CommandBuilder<T, U> | undefined;
/** string (or array of strings) that executes this command when given on the command line, first string may contain positional args */
command?: readonly string[] | string | undefined;
/** boolean (or string) to show deprecation notice */
deprecated?: boolean | string | undefined;
/** string used as the description for the command in help text, use `false` for a hidden command */
describe?: string | false | undefined;
/** a function which will be passed the parsed argv. */
handler: (args: ArgumentsCamelCase<U>) => void | Promise<void>;
}
type ParseCallback<T = {}> = (
err: Error | undefined,
argv: ArgumentsCamelCase<T>,
output: string,
) => void | Promise<void>;
type CommandBuilder<T = {}, U = {}> =
| { [key: string]: Options }
| ((args: Argv<T>) => Argv<U>)
| ((args: Argv<T>) => PromiseLike<Argv<U>>);
type SyncCompletionFunction = (current: string, argv: any) => string[];
type AsyncCompletionFunction = (
current: string,
argv: any,
done: (completion: readonly string[]) => void,
) => void;
type PromiseCompletionFunction = (current: string, argv: any) => Promise<string[]>;
type FallbackCompletionFunction = (
current: string,
argv: any,
completionFilter: (onCompleted?: CompletionCallback) => any,
done: (completions: string[]) => any,
) => void;
type MiddlewareFunction<T = {}> = (args: ArgumentsCamelCase<T>) => void | Promise<void>;
type Choices = ReadonlyArray<string | number | true | undefined>;
type PositionalOptionsType = "boolean" | "number" | "string";
type CompletionCallback = (err: Error | null, completions: string[] | undefined) => void;
}
declare var yargs: yargs.Argv;
export = yargs;
|
declare module "path/posix" {
import path = require("path");
export = path;
}
declare module "path/win32" {
import path = require("path");
export = path;
}
/**
* The `node:path` module provides utilities for working with file and directory
* paths. It can be accessed using:
*
* ```js
* const path = require('node:path');
* ```
* @see [source](https://github.com/nodejs/node/blob/v20.2.0/lib/path.js)
*/
declare module "path" {
namespace path {
/**
* A parsed path object generated by path.parse() or consumed by path.format().
*/
interface ParsedPath {
/**
* The root of the path such as '/' or 'c:\'
*/
root: string;
/**
* The full directory path such as '/home/user/dir' or 'c:\path\dir'
*/
dir: string;
/**
* The file name including extension (if any) such as 'index.html'
*/
base: string;
/**
* The file extension (if any) such as '.html'
*/
ext: string;
/**
* The file name without extension (if any) such as 'index'
*/
name: string;
}
interface FormatInputPathObject {
/**
* The root of the path such as '/' or 'c:\'
*/
root?: string | undefined;
/**
* The full directory path such as '/home/user/dir' or 'c:\path\dir'
*/
dir?: string | undefined;
/**
* The file name including extension (if any) such as 'index.html'
*/
base?: string | undefined;
/**
* The file extension (if any) such as '.html'
*/
ext?: string | undefined;
/**
* The file name without extension (if any) such as 'index'
*/
name?: string | undefined;
}
interface PlatformPath {
/**
* Normalize a string path, reducing '..' and '.' parts.
* When multiple slashes are found, they're replaced by a single one; when the path contains a trailing slash, it is preserved. On Windows backslashes are used.
*
* @param path string path to normalize.
* @throws {TypeError} if `path` is not a string.
*/
normalize(path: string): string;
/**
* Join all arguments together and normalize the resulting path.
*
* @param paths paths to join.
* @throws {TypeError} if any of the path segments is not a string.
*/
join(...paths: string[]): string;
/**
* The right-most parameter is considered {to}. Other parameters are considered an array of {from}.
*
* Starting from leftmost {from} parameter, resolves {to} to an absolute path.
*
* If {to} isn't already absolute, {from} arguments are prepended in right to left order,
* until an absolute path is found. If after using all {from} paths still no absolute path is found,
* the current working directory is used as well. The resulting path is normalized,
* and trailing slashes are removed unless the path gets resolved to the root directory.
*
* @param paths A sequence of paths or path segments.
* @throws {TypeError} if any of the arguments is not a string.
*/
resolve(...paths: string[]): string;
/**
* Determines whether {path} is an absolute path. An absolute path will always resolve to the same location, regardless of the working directory.
*
* If the given {path} is a zero-length string, `false` will be returned.
*
* @param path path to te |
st.
* @throws {TypeError} if `path` is not a string.
*/
isAbsolute(path: string): boolean;
/**
* Solve the relative path from {from} to {to} based on the current working directory.
* At times we have two absolute paths, and we need to derive the relative path from one to the other. This is actually the reverse transform of path.resolve.
*
* @throws {TypeError} if either `from` or `to` is not a string.
*/
relative(from: string, to: string): string;
/**
* Return the directory name of a path. Similar to the Unix dirname command.
*
* @param path the path to evaluate.
* @throws {TypeError} if `path` is not a string.
*/
dirname(path: string): string;
/**
* Return the last portion of a path. Similar to the Unix basename command.
* Often used to extract the file name from a fully qualified path.
*
* @param path the path to evaluate.
* @param suffix optionally, an extension to remove from the result.
* @throws {TypeError} if `path` is not a string or if `ext` is given and is not a string.
*/
basename(path: string, suffix?: string): string;
/**
* Return the extension of the path, from the last '.' to end of string in the last portion of the path.
* If there is no '.' in the last portion of the path or the first character of it is '.', then it returns an empty string.
*
* @param path the path to evaluate.
* @throws {TypeError} if `path` is not a string.
*/
extname(path: string): string;
/**
* The platform-specific file separator. '\\' or '/'.
*/
readonly sep: "\\" | "/";
/**
* The platform-specific file delimiter. ';' or ':'.
*/
readonly delimiter: ";" | ":";
/**
* Returns an object from a path string - the opposite of format().
*
* @param path path to evaluate.
* @throws {TypeError} if `path` is not a string.
*/
parse(path: string): ParsedPath;
/**
* Returns a path string from an object - the opposite of parse().
*
* @param pathObject path to evaluate.
*/
format(pathObject: FormatInputPathObject): string;
/**
* On Windows systems only, returns an equivalent namespace-prefixed path for the given path.
* If path is not a string, path will be returned without modifications.
* This method is meaningful only on Windows system.
* On POSIX systems, the method is non-operational and always returns path without modifications.
*/
toNamespacedPath(path: string): string;
/**
* Posix specific pathing.
* Same as parent object on posix.
*/
readonly posix: PlatformPath;
/**
* Windows specific pathing.
* Same as parent object on windows
*/
readonly win32: PlatformPath;
}
}
const path: path.PlatformPath;
export = path;
}
declare module "node:path" {
import path = require("path");
export = path;
}
declare module "node:path/posix" {
import path = require("path/posix");
export = path;
}
declare module "node:path/win32" {
import path = require("path/win32");
export = path;
}
|
/** @deprecated since v6.3.0 - use constants property exposed by the relevant module instead. */
declare module "constants" {
import { constants as osConstants, SignalConstants } from "node:os";
import { constants as cryptoConstants } from "node:crypto";
import { constants as fsConstants } from "node:fs";
const exp:
& typeof osConstants.errno
& typeof osConstants.priority
& SignalConstants
& typeof cryptoConstants
& typeof fsConstants;
export = exp;
}
declare module "node:constants" {
import constants = require("constants");
export = constants;
}
|
/**
* **This module is pending deprecation.** Once a replacement API has been
* finalized, this module will be fully deprecated. Most developers should
* **not** have cause to use this module. Users who absolutely must have
* the functionality that domains provide may rely on it for the time being
* but should expect to have to migrate to a different solution
* in the future.
*
* Domains provide a way to handle multiple different IO operations as a
* single group. If any of the event emitters or callbacks registered to a
* domain emit an `'error'` event, or throw an error, then the domain object
* will be notified, rather than losing the context of the error in the`process.on('uncaughtException')` handler, or causing the program to
* exit immediately with an error code.
* @deprecated Since v1.4.2 - Deprecated
* @see [source](https://github.com/nodejs/node/blob/v20.2.0/lib/domain.js)
*/
declare module "domain" {
import EventEmitter = require("node:events");
/**
* The `Domain` class encapsulates the functionality of routing errors and
* uncaught exceptions to the active `Domain` object.
*
* To handle the errors that it catches, listen to its `'error'` event.
*/
class Domain extends EventEmitter {
/**
* An array of timers and event emitters that have been explicitly added
* to the domain.
*/
members: Array<EventEmitter | NodeJS.Timer>;
/**
* The `enter()` method is plumbing used by the `run()`, `bind()`, and`intercept()` methods to set the active domain. It sets `domain.active` and`process.domain` to the domain, and implicitly
* pushes the domain onto the domain
* stack managed by the domain module (see {@link exit} for details on the
* domain stack). The call to `enter()` delimits the beginning of a chain of
* asynchronous calls and I/O operations bound to a domain.
*
* Calling `enter()` changes only the active domain, and does not alter the domain
* itself. `enter()` and `exit()` can be called an arbitrary number of times on a
* single domain.
*/
enter(): void;
/**
* The `exit()` method exits the current domain, popping it off the domain stack.
* Any time execution is going to switch to the context of a different chain of
* asynchronous calls, it's important to ensure that the current domain is exited.
* The call to `exit()` delimits either the end of or an interruption to the chain
* of asynchronous calls and I/O operations bound to a domain.
*
* If there are multiple, nested domains bound to the current execution context,`exit()` will exit any domains nested within this domain.
*
* Calling `exit()` changes only the active domain, and does not alter the domain
* itself. `enter()` and `exit()` can be called an arbitrary number of times on a
* single domain.
*/
exit(): void;
/**
* Run the supplied function in the context of the domain, implicitly
* binding all event emitters, timers, and low-level requests that are
* created in that context. Optionally, arguments can be passed to
* the function.
*
* This is the most basic way to use a domain.
*
* ```js
* const domain = require('node:domain');
* const fs = require('node:fs');
* const d = domain.create();
* d.on('error', (er) => {
* console.error('Caught error!', er);
* });
* d.run(() => {
* process.nextTick(() => {
* setTimeout(() => { // Simulating some various async stuff
* fs.open('non-existent file', 'r', (er, fd) => {
* if (er) throw er;
* // proceed...
* });
* }, 100);
* });
* });
* `` |
`
*
* In this example, the `d.on('error')` handler will be triggered, rather
* than crashing the program.
*/
run<T>(fn: (...args: any[]) => T, ...args: any[]): T;
/**
* Explicitly adds an emitter to the domain. If any event handlers called by
* the emitter throw an error, or if the emitter emits an `'error'` event, it
* will be routed to the domain's `'error'` event, just like with implicit
* binding.
*
* This also works with timers that are returned from `setInterval()` and `setTimeout()`. If their callback function throws, it will be caught by
* the domain `'error'` handler.
*
* If the Timer or `EventEmitter` was already bound to a domain, it is removed
* from that one, and bound to this one instead.
* @param emitter emitter or timer to be added to the domain
*/
add(emitter: EventEmitter | NodeJS.Timer): void;
/**
* The opposite of {@link add}. Removes domain handling from the
* specified emitter.
* @param emitter emitter or timer to be removed from the domain
*/
remove(emitter: EventEmitter | NodeJS.Timer): void;
/**
* The returned function will be a wrapper around the supplied callback
* function. When the returned function is called, any errors that are
* thrown will be routed to the domain's `'error'` event.
*
* ```js
* const d = domain.create();
*
* function readSomeFile(filename, cb) {
* fs.readFile(filename, 'utf8', d.bind((er, data) => {
* // If this throws, it will also be passed to the domain.
* return cb(er, data ? JSON.parse(data) : null);
* }));
* }
*
* d.on('error', (er) => {
* // An error occurred somewhere. If we throw it now, it will crash the program
* // with the normal line number and stack message.
* });
* ```
* @param callback The callback function
* @return The bound function
*/
bind<T extends Function>(callback: T): T;
/**
* This method is almost identical to {@link bind}. However, in
* addition to catching thrown errors, it will also intercept `Error` objects sent as the first argument to the function.
*
* In this way, the common `if (err) return callback(err);` pattern can be replaced
* with a single error handler in a single place.
*
* ```js
* const d = domain.create();
*
* function readSomeFile(filename, cb) {
* fs.readFile(filename, 'utf8', d.intercept((data) => {
* // Note, the first argument is never passed to the
* // callback since it is assumed to be the 'Error' argument
* // and thus intercepted by the domain.
*
* // If this throws, it will also be passed to the domain
* // so the error-handling logic can be moved to the 'error'
* // event on the domain instead of being repeated throughout
* // the program.
* return cb(null, JSON.parse(data));
* }));
* }
*
* d.on('error', (er) => {
* // An error occurred somewhere. If we throw it now, it will crash the program
* // with the normal line number and stack message.
* });
* ```
* @param callback The callback function
* @return The intercepted function
*/
intercept<T extends Function>(callback: T): T;
}
function create(): Domain;
}
declare module "node:domain" {
export * from "domain";
}
|
/**
* The `node:diagnostics_channel` module provides an API to create named channels
* to report arbitrary message data for diagnostics purposes.
*
* It can be accessed using:
*
* ```js
* import diagnostics_channel from 'node:diagnostics_channel';
* ```
*
* It is intended that a module writer wanting to report diagnostics messages
* will create one or many top-level channels to report messages through.
* Channels may also be acquired at runtime but it is not encouraged
* due to the additional overhead of doing so. Channels may be exported for
* convenience, but as long as the name is known it can be acquired anywhere.
*
* If you intend for your module to produce diagnostics data for others to
* consume it is recommended that you include documentation of what named
* channels are used along with the shape of the message data. Channel names
* should generally include the module name to avoid collisions with data from
* other modules.
* @since v15.1.0, v14.17.0
* @see [source](https://github.com/nodejs/node/blob/v20.2.0/lib/diagnostics_channel.js)
*/
declare module "diagnostics_channel" {
import { AsyncLocalStorage } from "node:async_hooks";
/**
* Check if there are active subscribers to the named channel. This is helpful if
* the message you want to send might be expensive to prepare.
*
* This API is optional but helpful when trying to publish messages from very
* performance-sensitive code.
*
* ```js
* import diagnostics_channel from 'node:diagnostics_channel';
*
* if (diagnostics_channel.hasSubscribers('my-channel')) {
* // There are subscribers, prepare and publish message
* }
* ```
* @since v15.1.0, v14.17.0
* @param name The channel name
* @return If there are active subscribers
*/
function hasSubscribers(name: string | symbol): boolean;
/**
* This is the primary entry-point for anyone wanting to publish to a named
* channel. It produces a channel object which is optimized to reduce overhead at
* publish time as much as possible.
*
* ```js
* import diagnostics_channel from 'node:diagnostics_channel';
*
* const channel = diagnostics_channel.channel('my-channel');
* ```
* @since v15.1.0, v14.17.0
* @param name The channel name
* @return The named channel object
*/
function channel(name: string | symbol): Channel;
type ChannelListener = (message: unknown, name: string | symbol) => void;
/**
* Register a message handler to subscribe to this channel. This message handler
* will be run synchronously whenever a message is published to the channel. Any
* errors thrown in the message handler will trigger an `'uncaughtException'`.
*
* ```js
* import diagnostics_channel from 'node:diagnostics_channel';
*
* diagnostics_channel.subscribe('my-channel', (message, name) => {
* // Received data
* });
* ```
* @since v18.7.0, v16.17.0
* @param name The channel name
* @param onMessage The handler to receive channel messages
*/
function subscribe(name: string | symbol, onMessage: ChannelListener): void;
/**
* Remove a message handler previously registered to this channel with {@link subscribe}.
*
* ```js
* import diagnostics_channel from 'node:diagnostics_channel';
*
* function onMessage(message, name) {
* // Received data
* }
*
* diagnostics_channel.subscribe('my-channel', onMessage);
*
* diagnostics_channel.unsubscribe('my-channel', onMessage);
* ```
* @since v18.7.0, v16.17.0
* @param name The channel name
* @param onMessage The previous subscribed handler to remove
* @return `true` if the handler was found, `false` otherwise.
*/
function unsubscribe(name: string | symbol, onMessage: ChannelListener): boolean;
/**
* Creates a `TracingChannel` wrapper for t |
he given `TracingChannel Channels`. If a name is given, the corresponding tracing
* channels will be created in the form of `tracing:${name}:${eventType}` where`eventType` corresponds to the types of `TracingChannel Channels`.
*
* ```js
* import diagnostics_channel from 'node:diagnostics_channel';
*
* const channelsByName = diagnostics_channel.tracingChannel('my-channel');
*
* // or...
*
* const channelsByCollection = diagnostics_channel.tracingChannel({
* start: diagnostics_channel.channel('tracing:my-channel:start'),
* end: diagnostics_channel.channel('tracing:my-channel:end'),
* asyncStart: diagnostics_channel.channel('tracing:my-channel:asyncStart'),
* asyncEnd: diagnostics_channel.channel('tracing:my-channel:asyncEnd'),
* error: diagnostics_channel.channel('tracing:my-channel:error'),
* });
* ```
* @since v19.9.0
* @experimental
* @param nameOrChannels Channel name or object containing all the `TracingChannel Channels`
* @return Collection of channels to trace with
*/
function tracingChannel<
StoreType = unknown,
ContextType extends object = StoreType extends object ? StoreType : object,
>(
nameOrChannels: string | TracingChannelCollection<StoreType, ContextType>,
): TracingChannel<StoreType, ContextType>;
/**
* The class `Channel` represents an individual named channel within the data
* pipeline. It is used to track subscribers and to publish messages when there
* are subscribers present. It exists as a separate object to avoid channel
* lookups at publish time, enabling very fast publish speeds and allowing
* for heavy use while incurring very minimal cost. Channels are created with {@link channel}, constructing a channel directly
* with `new Channel(name)` is not supported.
* @since v15.1.0, v14.17.0
*/
class Channel<StoreType = unknown, ContextType = StoreType> {
readonly name: string | symbol;
/**
* Check if there are active subscribers to this channel. This is helpful if
* the message you want to send might be expensive to prepare.
*
* This API is optional but helpful when trying to publish messages from very
* performance-sensitive code.
*
* ```js
* import diagnostics_channel from 'node:diagnostics_channel';
*
* const channel = diagnostics_channel.channel('my-channel');
*
* if (channel.hasSubscribers) {
* // There are subscribers, prepare and publish message
* }
* ```
* @since v15.1.0, v14.17.0
*/
readonly hasSubscribers: boolean;
private constructor(name: string | symbol);
/**
* Publish a message to any subscribers to the channel. This will trigger
* message handlers synchronously so they will execute within the same context.
*
* ```js
* import diagnostics_channel from 'node:diagnostics_channel';
*
* const channel = diagnostics_channel.channel('my-channel');
*
* channel.publish({
* some: 'message',
* });
* ```
* @since v15.1.0, v14.17.0
* @param message The message to send to the channel subscribers
*/
publish(message: unknown): void;
/**
* Register a message handler to subscribe to this channel. This message handler
* will be run synchronously whenever a message is published to the channel. Any
* errors thrown in the message handler will trigger an `'uncaughtException'`.
*
* ```js
* import diagnostics_channel from 'node:diagnostics_channel';
*
* const channel = diagnostics_channel.channel('my-channel');
*
* channel.subscribe((message, name) => {
* // Received data
|
* });
* ```
* @since v15.1.0, v14.17.0
* @deprecated Since v18.7.0,v16.17.0 - Use {@link subscribe(name, onMessage)}
* @param onMessage The handler to receive channel messages
*/
subscribe(onMessage: ChannelListener): void;
/**
* Remove a message handler previously registered to this channel with `channel.subscribe(onMessage)`.
*
* ```js
* import diagnostics_channel from 'node:diagnostics_channel';
*
* const channel = diagnostics_channel.channel('my-channel');
*
* function onMessage(message, name) {
* // Received data
* }
*
* channel.subscribe(onMessage);
*
* channel.unsubscribe(onMessage);
* ```
* @since v15.1.0, v14.17.0
* @deprecated Since v18.7.0,v16.17.0 - Use {@link unsubscribe(name, onMessage)}
* @param onMessage The previous subscribed handler to remove
* @return `true` if the handler was found, `false` otherwise.
*/
unsubscribe(onMessage: ChannelListener): void;
/**
* When `channel.runStores(context, ...)` is called, the given context data
* will be applied to any store bound to the channel. If the store has already been
* bound the previous `transform` function will be replaced with the new one.
* The `transform` function may be omitted to set the given context data as the
* context directly.
*
* ```js
* import diagnostics_channel from 'node:diagnostics_channel';
* import { AsyncLocalStorage } from 'node:async_hooks';
*
* const store = new AsyncLocalStorage();
*
* const channel = diagnostics_channel.channel('my-channel');
*
* channel.bindStore(store, (data) => {
* return { data };
* });
* ```
* @since v19.9.0
* @experimental
* @param store The store to which to bind the context data
* @param transform Transform context data before setting the store context
*/
bindStore(store: AsyncLocalStorage<StoreType>, transform?: (context: ContextType) => StoreType): void;
/**
* Remove a message handler previously registered to this channel with `channel.bindStore(store)`.
*
* ```js
* import diagnostics_channel from 'node:diagnostics_channel';
* import { AsyncLocalStorage } from 'node:async_hooks';
*
* const store = new AsyncLocalStorage();
*
* const channel = diagnostics_channel.channel('my-channel');
*
* channel.bindStore(store);
* channel.unbindStore(store);
* ```
* @since v19.9.0
* @experimental
* @param store The store to unbind from the channel.
* @return `true` if the store was found, `false` otherwise.
*/
unbindStore(store: any): void;
/**
* Applies the given data to any AsyncLocalStorage instances bound to the channel
* for the duration of the given function, then publishes to the channel within
* the scope of that data is applied to the stores.
*
* If a transform function was given to `channel.bindStore(store)` it will be
* applied to transform the message data before it becomes the context value for
* the store. The prior storage context is accessible from within the transform
* function in cases where context linking is required.
*
* The context applied to the store should be accessible in any async code which
* continues from execution which began during the given function, however
* there are some situations in which `context loss` may occur.
*
* ```js
* import diagnostics_channel from 'node:diagnostics_channel';
* import { |
AsyncLocalStorage } from 'node:async_hooks';
*
* const store = new AsyncLocalStorage();
*
* const channel = diagnostics_channel.channel('my-channel');
*
* channel.bindStore(store, (message) => {
* const parent = store.getStore();
* return new Span(message, parent);
* });
* channel.runStores({ some: 'message' }, () => {
* store.getStore(); // Span({ some: 'message' })
* });
* ```
* @since v19.9.0
* @experimental
* @param context Message to send to subscribers and bind to stores
* @param fn Handler to run within the entered storage context
* @param thisArg The receiver to be used for the function call.
* @param args Optional arguments to pass to the function.
*/
runStores(): void;
}
interface TracingChannelSubscribers<ContextType extends object> {
start: (message: ContextType) => void;
end: (
message: ContextType & {
error?: unknown;
result?: unknown;
},
) => void;
asyncStart: (
message: ContextType & {
error?: unknown;
result?: unknown;
},
) => void;
asyncEnd: (
message: ContextType & {
error?: unknown;
result?: unknown;
},
) => void;
error: (
message: ContextType & {
error: unknown;
},
) => void;
}
interface TracingChannelCollection<StoreType = unknown, ContextType = StoreType> {
start: Channel<StoreType, ContextType>;
end: Channel<StoreType, ContextType>;
asyncStart: Channel<StoreType, ContextType>;
asyncEnd: Channel<StoreType, ContextType>;
error: Channel<StoreType, ContextType>;
}
/**
* The class `TracingChannel` is a collection of `TracingChannel Channels` which
* together express a single traceable action. It is used to formalize and
* simplify the process of producing events for tracing application flow.{@link tracingChannel} is used to construct a`TracingChannel`. As with `Channel` it is recommended to create and reuse a
* single `TracingChannel` at the top-level of the file rather than creating them
* dynamically.
* @since v19.9.0
* @experimental
*/
class TracingChannel<StoreType = unknown, ContextType extends object = {}> implements TracingChannelCollection {
start: Channel<StoreType, ContextType>;
end: Channel<StoreType, ContextType>;
asyncStart: Channel<StoreType, ContextType>;
asyncEnd: Channel<StoreType, ContextType>;
error: Channel<StoreType, ContextType>;
/**
* Helper to subscribe a collection of functions to the corresponding channels.
* This is the same as calling `channel.subscribe(onMessage)` on each channel
* individually.
*
* ```js
* import diagnostics_channel from 'node:diagnostics_channel';
*
* const channels = diagnostics_channel.tracingChannel('my-channel');
*
* channels.subscribe({
* start(message) {
* // Handle start message
* },
* end(message) {
* // Handle end message
* },
* asyncStart(message) {
* // Handle asyncStart message
* },
* asyncEnd(message) {
* // Handle asyncEnd message
* },
* error(message) {
* // Handle error message
* },
* });
* ```
* @since v19.9.0
* @experimental
* @param subscribers Set of `TracingChannel Channels` subscribers
*/
subscribe(subscribers: TracingChannelSubscribers<ContextType>): void;
/**
* Helper to unsubscribe |
a collection of functions from the corresponding channels.
* This is the same as calling `channel.unsubscribe(onMessage)` on each channel
* individually.
*
* ```js
* import diagnostics_channel from 'node:diagnostics_channel';
*
* const channels = diagnostics_channel.tracingChannel('my-channel');
*
* channels.unsubscribe({
* start(message) {
* // Handle start message
* },
* end(message) {
* // Handle end message
* },
* asyncStart(message) {
* // Handle asyncStart message
* },
* asyncEnd(message) {
* // Handle asyncEnd message
* },
* error(message) {
* // Handle error message
* },
* });
* ```
* @since v19.9.0
* @experimental
* @param subscribers Set of `TracingChannel Channels` subscribers
* @return `true` if all handlers were successfully unsubscribed, and `false` otherwise.
*/
unsubscribe(subscribers: TracingChannelSubscribers<ContextType>): void;
/**
* Trace a synchronous function call. This will always produce a `start event` and `end event` around the execution and may produce an `error event` if the given function throws an error.
* This will run the given function using `channel.runStores(context, ...)` on the `start` channel which ensures all
* events should have any bound stores set to match this trace context.
*
* ```js
* import diagnostics_channel from 'node:diagnostics_channel';
*
* const channels = diagnostics_channel.tracingChannel('my-channel');
*
* channels.traceSync(() => {
* // Do something
* }, {
* some: 'thing',
* });
* ```
* @since v19.9.0
* @experimental
* @param fn Function to wrap a trace around
* @param context Shared object to correlate events through
* @param thisArg The receiver to be used for the function call
* @param args Optional arguments to pass to the function
* @return The return value of the given function
*/
traceSync<ThisArg = any, Args extends any[] = any[]>(
fn: (this: ThisArg, ...args: Args) => any,
context?: ContextType,
thisArg?: ThisArg,
...args: Args
): void;
/**
* Trace a promise-returning function call. This will always produce a `start event` and `end event` around the synchronous portion of the
* function execution, and will produce an `asyncStart event` and `asyncEnd event` when a promise continuation is reached. It may also
* produce an `error event` if the given function throws an error or the
* returned promise rejects. This will run the given function using `channel.runStores(context, ...)` on the `start` channel which ensures all
* events should have any bound stores set to match this trace context.
*
* ```js
* import diagnostics_channel from 'node:diagnostics_channel';
*
* const channels = diagnostics_channel.tracingChannel('my-channel');
*
* channels.tracePromise(async () => {
* // Do something
* }, {
* some: 'thing',
* });
* ```
* @since v19.9.0
* @experimental
* @param fn Promise-returning function to wrap a trace around
* @param context Shared object to correlate trace events through
* @param thisArg The receiver to be used for the function call
* @param args Optional arguments to pass to the function
* @return Chained from promise returned by the given function
*/
tracePromise<ThisArg = any, Args extends any[] = any[]>(
|
fn: (this: ThisArg, ...args: Args) => Promise<any>,
context?: ContextType,
thisArg?: ThisArg,
...args: Args
): void;
/**
* Trace a callback-receiving function call. This will always produce a `start event` and `end event` around the synchronous portion of the
* function execution, and will produce a `asyncStart event` and `asyncEnd event` around the callback execution. It may also produce an `error event` if the given function throws an error or
* the returned
* promise rejects. This will run the given function using `channel.runStores(context, ...)` on the `start` channel which ensures all
* events should have any bound stores set to match this trace context.
*
* The `position` will be -1 by default to indicate the final argument should
* be used as the callback.
*
* ```js
* import diagnostics_channel from 'node:diagnostics_channel';
*
* const channels = diagnostics_channel.tracingChannel('my-channel');
*
* channels.traceCallback((arg1, callback) => {
* // Do something
* callback(null, 'result');
* }, 1, {
* some: 'thing',
* }, thisArg, arg1, callback);
* ```
*
* The callback will also be run with `channel.runStores(context, ...)` which
* enables context loss recovery in some cases.
*
* ```js
* import diagnostics_channel from 'node:diagnostics_channel';
* import { AsyncLocalStorage } from 'node:async_hooks';
*
* const channels = diagnostics_channel.tracingChannel('my-channel');
* const myStore = new AsyncLocalStorage();
*
* // The start channel sets the initial store data to something
* // and stores that store data value on the trace context object
* channels.start.bindStore(myStore, (data) => {
* const span = new Span(data);
* data.span = span;
* return span;
* });
*
* // Then asyncStart can restore from that data it stored previously
* channels.asyncStart.bindStore(myStore, (data) => {
* return data.span;
* });
* ```
* @since v19.9.0
* @experimental
* @param fn callback using function to wrap a trace around
* @param position Zero-indexed argument position of expected callback
* @param context Shared object to correlate trace events through
* @param thisArg The receiver to be used for the function call
* @param args Optional arguments to pass to the function
* @return The return value of the given function
*/
traceCallback<Fn extends (this: any, ...args: any) => any>(
fn: Fn,
position: number | undefined,
context: ContextType | undefined,
thisArg: any,
...args: Parameters<Fn>
): void;
}
}
declare module "node:diagnostics_channel" {
export * from "diagnostics_channel";
}
|
export {}; // Make this a module
// #region Fetch and friends
// Conditional type aliases, used at the end of this file.
// Will either be empty if lib-dom is included, or the undici version otherwise.
type _Request = typeof globalThis extends { onmessage: any } ? {} : import("undici-types").Request;
type _Response = typeof globalThis extends { onmessage: any } ? {} : import("undici-types").Response;
type _FormData = typeof globalThis extends { onmessage: any } ? {} : import("undici-types").FormData;
type _Headers = typeof globalThis extends { onmessage: any } ? {} : import("undici-types").Headers;
type _RequestInit = typeof globalThis extends { onmessage: any } ? {}
: import("undici-types").RequestInit;
type _ResponseInit = typeof globalThis extends { onmessage: any } ? {}
: import("undici-types").ResponseInit;
type _File = typeof globalThis extends { onmessage: any } ? {} : import("node:buffer").File;
// #endregion Fetch and friends
declare global {
// Declare "static" methods in Error
interface ErrorConstructor {
/** Create .stack property on a target object */
captureStackTrace(targetObject: object, constructorOpt?: Function): void;
/**
* Optional override for formatting stack traces
*
* @see https://v8.dev/docs/stack-trace-api#customizing-stack-traces
*/
prepareStackTrace?: ((err: Error, stackTraces: NodeJS.CallSite[]) => any) | undefined;
stackTraceLimit: number;
}
/*-----------------------------------------------*
* *
* GLOBAL *
* *
------------------------------------------------*/
// For backwards compability
interface NodeRequire extends NodeJS.Require {}
interface RequireResolve extends NodeJS.RequireResolve {}
interface NodeModule extends NodeJS.Module {}
var process: NodeJS.Process;
var console: Console;
var __filename: string;
var __dirname: string;
var require: NodeRequire;
var module: NodeModule;
// Same as module.exports
var exports: any;
/**
* Only available if `--expose-gc` is passed to the process.
*/
var gc: undefined | (() => void);
// #region borrowed
// from https://github.com/microsoft/TypeScript/blob/38da7c600c83e7b31193a62495239a0fe478cb67/lib/lib.webworker.d.ts#L633 until moved to separate lib
/** A controller object that allows you to abort one or more DOM requests as and when desired. */
interface AbortController {
/**
* Returns the AbortSignal object associated with this object.
*/
readonly signal: AbortSignal;
/**
* Invoking this method will set this object's AbortSignal's aborted flag and signal to any observers that the associated activity is to be aborted.
*/
abort(reason?: any): void;
}
/** A signal object that allows you to communicate with a DOM request (such as a Fetch) and abort it if required via an AbortController object. */
interface AbortSignal extends EventTarget {
/**
* Returns true if this AbortSignal's AbortController has signaled to abort, and false otherwise.
*/
readonly aborted: boolean;
readonly reason: any;
onabort: null | ((this: AbortSignal, event: Event) => any);
throwIfAborted(): void;
}
var AbortController: typeof globalThis extends { onmessage: any; AbortController: infer T } ? T
: {
prototype: AbortController;
new(): AbortController;
};
var AbortSignal: typeof globalThis extends { onmessage: any; AbortSignal: infer T } ? T
: {
prototype: AbortSignal;
new(): AbortSignal;
abort(reason?: any): AbortSignal;
timeout(milliseconds: number): AbortSignal;
};
// #endregion borrowed
|
// #region Disposable
interface SymbolConstructor {
/**
* A method that is used to release resources held by an object. Called by the semantics of the `using` statement.
*/
readonly dispose: unique symbol;
/**
* A method that is used to asynchronously release resources held by an object. Called by the semantics of the `await using` statement.
*/
readonly asyncDispose: unique symbol;
}
interface Disposable {
[Symbol.dispose](): void;
}
interface AsyncDisposable {
[Symbol.asyncDispose](): PromiseLike<void>;
}
// #endregion Disposable
// #region ArrayLike.at()
interface RelativeIndexable<T> {
/**
* Takes an integer value and returns the item at that index,
* allowing for positive and negative integers.
* Negative integers count back from the last item in the array.
*/
at(index: number): T | undefined;
}
interface String extends RelativeIndexable<string> {}
interface Array<T> extends RelativeIndexable<T> {}
interface ReadonlyArray<T> extends RelativeIndexable<T> {}
interface Int8Array extends RelativeIndexable<number> {}
interface Uint8Array extends RelativeIndexable<number> {}
interface Uint8ClampedArray extends RelativeIndexable<number> {}
interface Int16Array extends RelativeIndexable<number> {}
interface Uint16Array extends RelativeIndexable<number> {}
interface Int32Array extends RelativeIndexable<number> {}
interface Uint32Array extends RelativeIndexable<number> {}
interface Float32Array extends RelativeIndexable<number> {}
interface Float64Array extends RelativeIndexable<number> {}
interface BigInt64Array extends RelativeIndexable<bigint> {}
interface BigUint64Array extends RelativeIndexable<bigint> {}
// #endregion ArrayLike.at() end
/**
* @since v17.0.0
*
* Creates a deep clone of an object.
*/
function structuredClone<T>(
value: T,
transfer?: { transfer: ReadonlyArray<import("worker_threads").TransferListItem> },
): T;
/*----------------------------------------------*
* *
* GLOBAL INTERFACES *
* *
*-----------------------------------------------*/
namespace NodeJS {
interface CallSite {
/**
* Value of "this"
*/
getThis(): unknown;
/**
* Type of "this" as a string.
* This is the name of the function stored in the constructor field of
* "this", if available. Otherwise the object's [[Class]] internal
* property.
*/
getTypeName(): string | null;
/**
* Current function
*/
getFunction(): Function | undefined;
/**
* Name of the current function, typically its name property.
* If a name property is not available an attempt will be made to try
* to infer a name from the function's context.
*/
getFunctionName(): string | null;
/**
* Name of the property [of "this" or one of its prototypes] that holds
* the current function
*/
getMethodName(): string | null;
/**
* Name of the script [if this function was defined in a script]
*/
getFileName(): string | undefined;
/**
* Current line number [if this function was defined in a script]
*/
getLineNumber(): number | null;
/**
* Current column number [if this function was defined in a script]
*/
getColumnNumber(): number | null;
/**
* A call site object |
representing the location where eval was called
* [if this function was created using a call to eval]
*/
getEvalOrigin(): string | undefined;
/**
* Is this a toplevel invocation, that is, is "this" the global object?
*/
isToplevel(): boolean;
/**
* Does this call take place in code defined by a call to eval?
*/
isEval(): boolean;
/**
* Is this call in native V8 code?
*/
isNative(): boolean;
/**
* Is this a constructor call?
*/
isConstructor(): boolean;
/**
* is this an async call (i.e. await, Promise.all(), or Promise.any())?
*/
isAsync(): boolean;
/**
* is this an async call to Promise.all()?
*/
isPromiseAll(): boolean;
/**
* returns the index of the promise element that was followed in
* Promise.all() or Promise.any() for async stack traces, or null
* if the CallSite is not an async
*/
getPromiseIndex(): number | null;
getScriptNameOrSourceURL(): string;
getScriptHash(): string;
getEnclosingColumnNumber(): number;
getEnclosingLineNumber(): number;
getPosition(): number;
toString(): string;
}
interface ErrnoException extends Error {
errno?: number | undefined;
code?: string | undefined;
path?: string | undefined;
syscall?: string | undefined;
}
interface ReadableStream extends EventEmitter {
readable: boolean;
read(size?: number): string | Buffer;
setEncoding(encoding: BufferEncoding): this;
pause(): this;
resume(): this;
isPaused(): boolean;
pipe<T extends WritableStream>(destination: T, options?: { end?: boolean | undefined }): T;
unpipe(destination?: WritableStream): this;
unshift(chunk: string | Uint8Array, encoding?: BufferEncoding): void;
wrap(oldStream: ReadableStream): this;
[Symbol.asyncIterator](): AsyncIterableIterator<string | Buffer>;
}
interface WritableStream extends EventEmitter {
writable: boolean;
write(buffer: Uint8Array | string, cb?: (err?: Error | null) => void): boolean;
write(str: string, encoding?: BufferEncoding, cb?: (err?: Error | null) => void): boolean;
end(cb?: () => void): this;
end(data: string | Uint8Array, cb?: () => void): this;
end(str: string, encoding?: BufferEncoding, cb?: () => void): this;
}
interface ReadWriteStream extends ReadableStream, WritableStream {}
interface RefCounted {
ref(): this;
unref(): this;
}
type TypedArray =
| Uint8Array
| Uint8ClampedArray
| Uint16Array
| Uint32Array
| Int8Array
| Int16Array
| Int32Array
| BigUint64Array
| BigInt64Array
| Float32Array
| Float64Array;
type ArrayBufferView = TypedArray | DataView;
interface Require {
(id: string): any;
resolve: RequireResolve;
cache: Dict<NodeModule>;
/**
* @deprecated
*/
extensions: RequireExtensions;
main: Module | undefined;
}
interface RequireResolve {
(id: string, options?: { paths?: string[] | undefined }): string;
paths(request: string): string[] | null;
}
interface RequireExtensions extends Dict<(m: Module, filename: string) => any> {
".js": (m: Mo |
dule, filename: string) => any;
".json": (m: Module, filename: string) => any;
".node": (m: Module, filename: string) => any;
}
interface Module {
/**
* `true` if the module is running during the Node.js preload
*/
isPreloading: boolean;
exports: any;
require: Require;
id: string;
filename: string;
loaded: boolean;
/** @deprecated since v14.6.0 Please use `require.main` and `module.children` instead. */
parent: Module | null | undefined;
children: Module[];
/**
* @since v11.14.0
*
* The directory name of the module. This is usually the same as the path.dirname() of the module.id.
*/
path: string;
paths: string[];
}
interface Dict<T> {
[key: string]: T | undefined;
}
interface ReadOnlyDict<T> {
readonly [key: string]: T | undefined;
}
}
interface RequestInit extends _RequestInit {}
function fetch(
input: string | URL | globalThis.Request,
init?: RequestInit,
): Promise<Response>;
interface Request extends _Request {}
var Request: typeof globalThis extends {
onmessage: any;
Request: infer T;
} ? T
: typeof import("undici-types").Request;
interface ResponseInit extends _ResponseInit {}
interface Response extends _Response {}
var Response: typeof globalThis extends {
onmessage: any;
Response: infer T;
} ? T
: typeof import("undici-types").Response;
interface FormData extends _FormData {}
var FormData: typeof globalThis extends {
onmessage: any;
FormData: infer T;
} ? T
: typeof import("undici-types").FormData;
interface Headers extends _Headers {}
var Headers: typeof globalThis extends {
onmessage: any;
Headers: infer T;
} ? T
: typeof import("undici-types").Headers;
interface File extends _File {}
var File: typeof globalThis extends {
onmessage: any;
File: infer T;
} ? T
: typeof import("node:buffer").File;
}
|
/**
* The `node:tls` module provides an implementation of the Transport Layer Security
* (TLS) and Secure Socket Layer (SSL) protocols that is built on top of OpenSSL.
* The module can be accessed using:
*
* ```js
* const tls = require('node:tls');
* ```
* @see [source](https://github.com/nodejs/node/blob/v20.2.0/lib/tls.js)
*/
declare module "tls" {
import { X509Certificate } from "node:crypto";
import * as net from "node:net";
import * as stream from "stream";
const CLIENT_RENEG_LIMIT: number;
const CLIENT_RENEG_WINDOW: number;
interface Certificate {
/**
* Country code.
*/
C: string;
/**
* Street.
*/
ST: string;
/**
* Locality.
*/
L: string;
/**
* Organization.
*/
O: string;
/**
* Organizational unit.
*/
OU: string;
/**
* Common name.
*/
CN: string;
}
interface PeerCertificate {
/**
* `true` if a Certificate Authority (CA), `false` otherwise.
* @since v18.13.0
*/
ca: boolean;
/**
* The DER encoded X.509 certificate data.
*/
raw: Buffer;
/**
* The certificate subject.
*/
subject: Certificate;
/**
* The certificate issuer, described in the same terms as the `subject`.
*/
issuer: Certificate;
/**
* The date-time the certificate is valid from.
*/
valid_from: string;
/**
* The date-time the certificate is valid to.
*/
valid_to: string;
/**
* The certificate serial number, as a hex string.
*/
serialNumber: string;
/**
* The SHA-1 digest of the DER encoded certificate.
* It is returned as a `:` separated hexadecimal string.
*/
fingerprint: string;
/**
* The SHA-256 digest of the DER encoded certificate.
* It is returned as a `:` separated hexadecimal string.
*/
fingerprint256: string;
/**
* The SHA-512 digest of the DER encoded certificate.
* It is returned as a `:` separated hexadecimal string.
*/
fingerprint512: string;
/**
* The extended key usage, a set of OIDs.
*/
ext_key_usage?: string[];
/**
* A string containing concatenated names for the subject,
* an alternative to the `subject` names.
*/
subjectaltname?: string;
/**
* An array describing the AuthorityInfoAccess, used with OCSP.
*/
infoAccess?: NodeJS.Dict<string[]>;
/**
* For RSA keys: The RSA bit size.
*
* For EC keys: The key size in bits.
*/
bits?: number;
/**
* The RSA exponent, as a string in hexadecimal number notation.
*/
exponent?: string;
/**
* The RSA modulus, as a hexadecimal string.
*/
modulus?: string;
/**
* The public key.
*/
pubkey?: Buffer;
/**
* The ASN.1 name of the OID of the elliptic curve.
* Well-known curves are identified by an OID.
* While it is unusual, it is possible that the curve
* is identified by its mathematical properties,
* in which case it will not have an OID.
*/
asn1Curve?: string;
/**
* The NIST name for the elliptic curve,if it has one
* (not all well-known curves have been assigned names by NIST).
*/
nistCurve?: string;
}
interface DetailedPeerCertificate extends PeerCertificate {
/**
* The issuer certificate object.
* For self-signed certificates, this may be a circular reference.
*/
issuerCertificate |
: DetailedPeerCertificate;
}
interface CipherNameAndProtocol {
/**
* The cipher name.
*/
name: string;
/**
* SSL/TLS protocol version.
*/
version: string;
/**
* IETF name for the cipher suite.
*/
standardName: string;
}
interface EphemeralKeyInfo {
/**
* The supported types are 'DH' and 'ECDH'.
*/
type: string;
/**
* The name property is available only when type is 'ECDH'.
*/
name?: string | undefined;
/**
* The size of parameter of an ephemeral key exchange.
*/
size: number;
}
interface KeyObject {
/**
* Private keys in PEM format.
*/
pem: string | Buffer;
/**
* Optional passphrase.
*/
passphrase?: string | undefined;
}
interface PxfObject {
/**
* PFX or PKCS12 encoded private key and certificate chain.
*/
buf: string | Buffer;
/**
* Optional passphrase.
*/
passphrase?: string | undefined;
}
interface TLSSocketOptions extends SecureContextOptions, CommonConnectionOptions {
/**
* If true the TLS socket will be instantiated in server-mode.
* Defaults to false.
*/
isServer?: boolean | undefined;
/**
* An optional net.Server instance.
*/
server?: net.Server | undefined;
/**
* An optional Buffer instance containing a TLS session.
*/
session?: Buffer | undefined;
/**
* If true, specifies that the OCSP status request extension will be
* added to the client hello and an 'OCSPResponse' event will be
* emitted on the socket before establishing a secure communication
*/
requestOCSP?: boolean | undefined;
}
/**
* Performs transparent encryption of written data and all required TLS
* negotiation.
*
* Instances of `tls.TLSSocket` implement the duplex `Stream` interface.
*
* Methods that return TLS connection metadata (e.g.{@link TLSSocket.getPeerCertificate}) will only return data while the
* connection is open.
* @since v0.11.4
*/
class TLSSocket extends net.Socket {
/**
* Construct a new tls.TLSSocket object from an existing TCP socket.
*/
constructor(socket: net.Socket | stream.Duplex, options?: TLSSocketOptions);
/**
* This property is `true` if the peer certificate was signed by one of the CAs
* specified when creating the `tls.TLSSocket` instance, otherwise `false`.
* @since v0.11.4
*/
authorized: boolean;
/**
* Returns the reason why the peer's certificate was not been verified. This
* property is set only when `tlsSocket.authorized === false`.
* @since v0.11.4
*/
authorizationError: Error;
/**
* Always returns `true`. This may be used to distinguish TLS sockets from regular`net.Socket` instances.
* @since v0.11.4
*/
encrypted: true;
/**
* String containing the selected ALPN protocol.
* Before a handshake has completed, this value is always null.
* When a handshake is completed but not ALPN protocol was selected, tlsSocket.alpnProtocol equals false.
*/
alpnProtocol: string | false | null;
/**
* Returns an object representing the local certificate. The returned object has
* some properties corresponding to the fields of the certificate.
*
* See {@link TLSSocket.getPeerCertificate} for an example of the certificate
* structure.
*
* If there is no local certificate, an empty object will be returned. If the
* socket has been destroyed, `null |
` will be returned.
* @since v11.2.0
*/
getCertificate(): PeerCertificate | object | null;
/**
* Returns an object containing information on the negotiated cipher suite.
*
* For example, a TLSv1.2 protocol with AES256-SHA cipher:
*
* ```json
* {
* "name": "AES256-SHA",
* "standardName": "TLS_RSA_WITH_AES_256_CBC_SHA",
* "version": "SSLv3"
* }
* ```
*
* See [SSL\_CIPHER\_get\_name](https://www.openssl.org/docs/man1.1.1/man3/SSL_CIPHER_get_name.html) for more information.
* @since v0.11.4
*/
getCipher(): CipherNameAndProtocol;
/**
* Returns an object representing the type, name, and size of parameter of
* an ephemeral key exchange in `perfect forward secrecy` on a client
* connection. It returns an empty object when the key exchange is not
* ephemeral. As this is only supported on a client socket; `null` is returned
* if called on a server socket. The supported types are `'DH'` and `'ECDH'`. The`name` property is available only when type is `'ECDH'`.
*
* For example: `{ type: 'ECDH', name: 'prime256v1', size: 256 }`.
* @since v5.0.0
*/
getEphemeralKeyInfo(): EphemeralKeyInfo | object | null;
/**
* As the `Finished` messages are message digests of the complete handshake
* (with a total of 192 bits for TLS 1.0 and more for SSL 3.0), they can
* be used for external authentication procedures when the authentication
* provided by SSL/TLS is not desired or is not enough.
*
* Corresponds to the `SSL_get_finished` routine in OpenSSL and may be used
* to implement the `tls-unique` channel binding from [RFC 5929](https://tools.ietf.org/html/rfc5929).
* @since v9.9.0
* @return The latest `Finished` message that has been sent to the socket as part of a SSL/TLS handshake, or `undefined` if no `Finished` message has been sent yet.
*/
getFinished(): Buffer | undefined;
/**
* Returns an object representing the peer's certificate. If the peer does not
* provide a certificate, an empty object will be returned. If the socket has been
* destroyed, `null` will be returned.
*
* If the full certificate chain was requested, each certificate will include an`issuerCertificate` property containing an object representing its issuer's
* certificate.
* @since v0.11.4
* @param detailed Include the full certificate chain if `true`, otherwise include just the peer's certificate.
* @return A certificate object.
*/
getPeerCertificate(detailed: true): DetailedPeerCertificate;
getPeerCertificate(detailed?: false): PeerCertificate;
getPeerCertificate(detailed?: boolean): PeerCertificate | DetailedPeerCertificate;
/**
* As the `Finished` messages are message digests of the complete handshake
* (with a total of 192 bits for TLS 1.0 and more for SSL 3.0), they can
* be used for external authentication procedures when the authentication
* provided by SSL/TLS is not desired or is not enough.
*
* Corresponds to the `SSL_get_peer_finished` routine in OpenSSL and may be used
* to implement the `tls-unique` channel binding from [RFC 5929](https://tools.ietf.org/html/rfc5929).
* @since v9.9.0
* @return The latest `Finished` message that is expected or has actually been received from the socket as part of a SSL/TLS handshake, or `undefined` if there is no `Finished` message so
* far.
*/
getPeerFinished(): Buffer | undefined;
/**
* Returns a string containing the negotiated SSL/TLS protocol version of the
* current connection. The valu |
e `'unknown'` will be returned for connected
* sockets that have not completed the handshaking process. The value `null` will
* be returned for server sockets or disconnected client sockets.
*
* Protocol versions are:
*
* * `'SSLv3'`
* * `'TLSv1'`
* * `'TLSv1.1'`
* * `'TLSv1.2'`
* * `'TLSv1.3'`
*
* See the OpenSSL [`SSL_get_version`](https://www.openssl.org/docs/man1.1.1/man3/SSL_get_version.html) documentation for more information.
* @since v5.7.0
*/
getProtocol(): string | null;
/**
* Returns the TLS session data or `undefined` if no session was
* negotiated. On the client, the data can be provided to the `session` option of {@link connect} to resume the connection. On the server, it may be useful
* for debugging.
*
* See `Session Resumption` for more information.
*
* Note: `getSession()` works only for TLSv1.2 and below. For TLSv1.3, applications
* must use the `'session'` event (it also works for TLSv1.2 and below).
* @since v0.11.4
*/
getSession(): Buffer | undefined;
/**
* See [SSL\_get\_shared\_sigalgs](https://www.openssl.org/docs/man1.1.1/man3/SSL_get_shared_sigalgs.html) for more information.
* @since v12.11.0
* @return List of signature algorithms shared between the server and the client in the order of decreasing preference.
*/
getSharedSigalgs(): string[];
/**
* For a client, returns the TLS session ticket if one is available, or`undefined`. For a server, always returns `undefined`.
*
* It may be useful for debugging.
*
* See `Session Resumption` for more information.
* @since v0.11.4
*/
getTLSTicket(): Buffer | undefined;
/**
* See `Session Resumption` for more information.
* @since v0.5.6
* @return `true` if the session was reused, `false` otherwise.
*/
isSessionReused(): boolean;
/**
* The `tlsSocket.renegotiate()` method initiates a TLS renegotiation process.
* Upon completion, the `callback` function will be passed a single argument
* that is either an `Error` (if the request failed) or `null`.
*
* This method can be used to request a peer's certificate after the secure
* connection has been established.
*
* When running as the server, the socket will be destroyed with an error after`handshakeTimeout` timeout.
*
* For TLSv1.3, renegotiation cannot be initiated, it is not supported by the
* protocol.
* @since v0.11.8
* @param callback If `renegotiate()` returned `true`, callback is attached once to the `'secure'` event. If `renegotiate()` returned `false`, `callback` will be called in the next tick with
* an error, unless the `tlsSocket` has been destroyed, in which case `callback` will not be called at all.
* @return `true` if renegotiation was initiated, `false` otherwise.
*/
renegotiate(
options: {
rejectUnauthorized?: boolean | undefined;
requestCert?: boolean | undefined;
},
callback: (err: Error | null) => void,
): undefined | boolean;
/**
* The `tlsSocket.setMaxSendFragment()` method sets the maximum TLS fragment size.
* Returns `true` if setting the limit succeeded; `false` otherwise.
*
* Smaller fragment sizes decrease the buffering latency on the client: larger
* fragments are buffered by the TLS layer until the entire fragment is received
* and its integrity is verified; large fragments can span multiple roundtrips
* and their processing can be delayed due to packet loss or reorderin |
g. However,
* smaller fragments add extra TLS framing bytes and CPU overhead, which may
* decrease overall server throughput.
* @since v0.11.11
* @param [size=16384] The maximum TLS fragment size. The maximum value is `16384`.
*/
setMaxSendFragment(size: number): boolean;
/**
* Disables TLS renegotiation for this `TLSSocket` instance. Once called, attempts
* to renegotiate will trigger an `'error'` event on the `TLSSocket`.
* @since v8.4.0
*/
disableRenegotiation(): void;
/**
* When enabled, TLS packet trace information is written to `stderr`. This can be
* used to debug TLS connection problems.
*
* The format of the output is identical to the output of`openssl s_client -trace` or `openssl s_server -trace`. While it is produced by
* OpenSSL's `SSL_trace()` function, the format is undocumented, can change
* without notice, and should not be relied on.
* @since v12.2.0
*/
enableTrace(): void;
/**
* Returns the peer certificate as an `X509Certificate` object.
*
* If there is no peer certificate, or the socket has been destroyed,`undefined` will be returned.
* @since v15.9.0
*/
getPeerX509Certificate(): X509Certificate | undefined;
/**
* Returns the local certificate as an `X509Certificate` object.
*
* If there is no local certificate, or the socket has been destroyed,`undefined` will be returned.
* @since v15.9.0
*/
getX509Certificate(): X509Certificate | undefined;
/**
* Keying material is used for validations to prevent different kind of attacks in
* network protocols, for example in the specifications of IEEE 802.1X.
*
* Example
*
* ```js
* const keyingMaterial = tlsSocket.exportKeyingMaterial(
* 128,
* 'client finished');
*
* /*
* Example return value of keyingMaterial:
* <Buffer 76 26 af 99 c5 56 8e 42 09 91 ef 9f 93 cb ad 6c 7b 65 f8 53 f1 d8 d9
* 12 5a 33 b8 b5 25 df 7b 37 9f e0 e2 4f b8 67 83 a3 2f cd 5d 41 42 4c 91
* 74 ef 2c ... 78 more bytes>
*
* ```
*
* See the OpenSSL [`SSL_export_keying_material`](https://www.openssl.org/docs/man1.1.1/man3/SSL_export_keying_material.html) documentation for more
* information.
* @since v13.10.0, v12.17.0
* @param length number of bytes to retrieve from keying material
* @param label an application specific label, typically this will be a value from the [IANA Exporter Label
* Registry](https://www.iana.org/assignments/tls-parameters/tls-parameters.xhtml#exporter-labels).
* @param context Optionally provide a context.
* @return requested bytes of the keying material
*/
exportKeyingMaterial(length: number, label: string, context: Buffer): Buffer;
addListener(event: string, listener: (...args: any[]) => void): this;
addListener(event: "OCSPResponse", listener: (response: Buffer) => void): this;
addListener(event: "secureConnect", listener: () => void): this;
addListener(event: "session", listener: (session: Buffer) => void): this;
addListener(event: "keylog", listener: (line: Buffer) => void): this;
emit(event: string | symbol, ...args: any[]): boolean;
emit(event: "OCSPResponse", response: Buffer): boolean;
emit(event: "secureConnect"): boolean;
emit(event: "session", session: Buffer): boolean;
emit(event: "keylog", line: Buffer): boolean;
on(event: string, listener: (...args: any[]) => void): this;
on(event: "OCSPResponse", listener: (response: Buffer) => void): this;
on(event: "secureConnect", listener: () |
=> void): this;
on(event: "session", listener: (session: Buffer) => void): this;
on(event: "keylog", listener: (line: Buffer) => void): this;
once(event: string, listener: (...args: any[]) => void): this;
once(event: "OCSPResponse", listener: (response: Buffer) => void): this;
once(event: "secureConnect", listener: () => void): this;
once(event: "session", listener: (session: Buffer) => void): this;
once(event: "keylog", listener: (line: Buffer) => void): this;
prependListener(event: string, listener: (...args: any[]) => void): this;
prependListener(event: "OCSPResponse", listener: (response: Buffer) => void): this;
prependListener(event: "secureConnect", listener: () => void): this;
prependListener(event: "session", listener: (session: Buffer) => void): this;
prependListener(event: "keylog", listener: (line: Buffer) => void): this;
prependOnceListener(event: string, listener: (...args: any[]) => void): this;
prependOnceListener(event: "OCSPResponse", listener: (response: Buffer) => void): this;
prependOnceListener(event: "secureConnect", listener: () => void): this;
prependOnceListener(event: "session", listener: (session: Buffer) => void): this;
prependOnceListener(event: "keylog", listener: (line: Buffer) => void): this;
}
interface CommonConnectionOptions {
/**
* An optional TLS context object from tls.createSecureContext()
*/
secureContext?: SecureContext | undefined;
/**
* When enabled, TLS packet trace information is written to `stderr`. This can be
* used to debug TLS connection problems.
* @default false
*/
enableTrace?: boolean | undefined;
/**
* If true the server will request a certificate from clients that
* connect and attempt to verify that certificate. Defaults to
* false.
*/
requestCert?: boolean | undefined;
/**
* An array of strings or a Buffer naming possible ALPN protocols.
* (Protocols should be ordered by their priority.)
*/
ALPNProtocols?: string[] | Uint8Array[] | Uint8Array | undefined;
/**
* SNICallback(servername, cb) <Function> A function that will be
* called if the client supports SNI TLS extension. Two arguments
* will be passed when called: servername and cb. SNICallback should
* invoke cb(null, ctx), where ctx is a SecureContext instance.
* (tls.createSecureContext(...) can be used to get a proper
* SecureContext.) If SNICallback wasn't provided the default callback
* with high-level API will be used (see below).
*/
SNICallback?: ((servername: string, cb: (err: Error | null, ctx?: SecureContext) => void) => void) | undefined;
/**
* If true the server will reject any connection which is not
* authorized with the list of supplied CAs. This option only has an
* effect if requestCert is true.
* @default true
*/
rejectUnauthorized?: boolean | undefined;
}
interface TlsOptions extends SecureContextOptions, CommonConnectionOptions, net.ServerOpts {
/**
* Abort the connection if the SSL/TLS handshake does not finish in the
* specified number of milliseconds. A 'tlsClientError' is emitted on
* the tls.Server object whenever a handshake times out. Default:
* 120000 (120 seconds).
*/
handshakeTimeout?: number | undefined;
/**
* The number of seconds after which a TLS session created by the
* server will no longer be resumable. See Session Resumption for more
* information. Default: 300.
*/
sessionTimeout?: number | undefined;
/**
* 48-bytes of cryptographically strong pseudo-random data.
*/
|
ticketKeys?: Buffer | undefined;
/**
* @param socket
* @param identity identity parameter sent from the client.
* @return pre-shared key that must either be
* a buffer or `null` to stop the negotiation process. Returned PSK must be
* compatible with the selected cipher's digest.
*
* When negotiating TLS-PSK (pre-shared keys), this function is called
* with the identity provided by the client.
* If the return value is `null` the negotiation process will stop and an
* "unknown_psk_identity" alert message will be sent to the other party.
* If the server wishes to hide the fact that the PSK identity was not known,
* the callback must provide some random data as `psk` to make the connection
* fail with "decrypt_error" before negotiation is finished.
* PSK ciphers are disabled by default, and using TLS-PSK thus
* requires explicitly specifying a cipher suite with the `ciphers` option.
* More information can be found in the RFC 4279.
*/
pskCallback?(socket: TLSSocket, identity: string): DataView | NodeJS.TypedArray | null;
/**
* hint to send to a client to help
* with selecting the identity during TLS-PSK negotiation. Will be ignored
* in TLS 1.3. Upon failing to set pskIdentityHint `tlsClientError` will be
* emitted with `ERR_TLS_PSK_SET_IDENTIY_HINT_FAILED` code.
*/
pskIdentityHint?: string | undefined;
}
interface PSKCallbackNegotation {
psk: DataView | NodeJS.TypedArray;
identity: string;
}
interface ConnectionOptions extends SecureContextOptions, CommonConnectionOptions {
host?: string | undefined;
port?: number | undefined;
path?: string | undefined; // Creates unix socket connection to path. If this option is specified, `host` and `port` are ignored.
socket?: stream.Duplex | undefined; // Establish secure connection on a given socket rather than creating a new socket
checkServerIdentity?: typeof checkServerIdentity | undefined;
servername?: string | undefined; // SNI TLS Extension
session?: Buffer | undefined;
minDHSize?: number | undefined;
lookup?: net.LookupFunction | undefined;
timeout?: number | undefined;
/**
* When negotiating TLS-PSK (pre-shared keys), this function is called
* with optional identity `hint` provided by the server or `null`
* in case of TLS 1.3 where `hint` was removed.
* It will be necessary to provide a custom `tls.checkServerIdentity()`
* for the connection as the default one will try to check hostname/IP
* of the server against the certificate but that's not applicable for PSK
* because there won't be a certificate present.
* More information can be found in the RFC 4279.
*
* @param hint message sent from the server to help client
* decide which identity to use during negotiation.
* Always `null` if TLS 1.3 is used.
* @returns Return `null` to stop the negotiation process. `psk` must be
* compatible with the selected cipher's digest.
* `identity` must use UTF-8 encoding.
*/
pskCallback?(hint: string | null): PSKCallbackNegotation | null;
}
/**
* Accepts encrypted connections using TLS or SSL.
* @since v0.3.2
*/
class Server extends net.Server {
constructor(secureConnectionListener?: (socket: TLSSocket) => void);
constructor(options: TlsOptions, secureConnectionListener?: (socket: TLSSocket) => void);
/**
* The `server.addContext()` method adds a secure context that will be used if
* the client request's SNI name matches the supplied `hostname` (or wildcard).
*
* When there are multiple matching contexts, the most rec |
ently added one is
* used.
* @since v0.5.3
* @param hostname A SNI host name or wildcard (e.g. `'*'`)
* @param context An object containing any of the possible properties from the {@link createSecureContext} `options` arguments (e.g. `key`, `cert`, `ca`, etc), or a TLS context object created
* with {@link createSecureContext} itself.
*/
addContext(hostname: string, context: SecureContextOptions): void;
/**
* Returns the session ticket keys.
*
* See `Session Resumption` for more information.
* @since v3.0.0
* @return A 48-byte buffer containing the session ticket keys.
*/
getTicketKeys(): Buffer;
/**
* The `server.setSecureContext()` method replaces the secure context of an
* existing server. Existing connections to the server are not interrupted.
* @since v11.0.0
* @param options An object containing any of the possible properties from the {@link createSecureContext} `options` arguments (e.g. `key`, `cert`, `ca`, etc).
*/
setSecureContext(options: SecureContextOptions): void;
/**
* Sets the session ticket keys.
*
* Changes to the ticket keys are effective only for future server connections.
* Existing or currently pending server connections will use the previous keys.
*
* See `Session Resumption` for more information.
* @since v3.0.0
* @param keys A 48-byte buffer containing the session ticket keys.
*/
setTicketKeys(keys: Buffer): void;
/**
* events.EventEmitter
* 1. tlsClientError
* 2. newSession
* 3. OCSPRequest
* 4. resumeSession
* 5. secureConnection
* 6. keylog
*/
addListener(event: string, listener: (...args: any[]) => void): this;
addListener(event: "tlsClientError", listener: (err: Error, tlsSocket: TLSSocket) => void): this;
addListener(
event: "newSession",
listener: (sessionId: Buffer, sessionData: Buffer, callback: () => void) => void,
): this;
addListener(
event: "OCSPRequest",
listener: (
certificate: Buffer,
issuer: Buffer,
callback: (err: Error | null, resp: Buffer) => void,
) => void,
): this;
addListener(
event: "resumeSession",
listener: (sessionId: Buffer, callback: (err: Error | null, sessionData: Buffer | null) => void) => void,
): this;
addListener(event: "secureConnection", listener: (tlsSocket: TLSSocket) => void): this;
addListener(event: "keylog", listener: (line: Buffer, tlsSocket: TLSSocket) => void): this;
emit(event: string | symbol, ...args: any[]): boolean;
emit(event: "tlsClientError", err: Error, tlsSocket: TLSSocket): boolean;
emit(event: "newSession", sessionId: Buffer, sessionData: Buffer, callback: () => void): boolean;
emit(
event: "OCSPRequest",
certificate: Buffer,
issuer: Buffer,
callback: (err: Error | null, resp: Buffer) => void,
): boolean;
emit(
event: "resumeSession",
sessionId: Buffer,
callback: (err: Error | null, sessionData: Buffer | null) => void,
): boolean;
emit(event: "secureConnection", tlsSocket: TLSSocket): boolean;
emit(event: "keylog", line: Buffer, tlsSocket: TLSSocket): boolean;
on(event: string, listener: (...args: any[]) => void): this;
on(event: "tlsClientError", listener: (err: Error, tlsSocket: TLSSocket) => void): this;
on(event: "newSession", listener: (sessionId: Buffer, sessionData: Buffer, callback: () => void) => void): this;
on(
event: "OCSPRequest",
listener: (
|
certificate: Buffer,
issuer: Buffer,
callback: (err: Error | null, resp: Buffer) => void,
) => void,
): this;
on(
event: "resumeSession",
listener: (sessionId: Buffer, callback: (err: Error | null, sessionData: Buffer | null) => void) => void,
): this;
on(event: "secureConnection", listener: (tlsSocket: TLSSocket) => void): this;
on(event: "keylog", listener: (line: Buffer, tlsSocket: TLSSocket) => void): this;
once(event: string, listener: (...args: any[]) => void): this;
once(event: "tlsClientError", listener: (err: Error, tlsSocket: TLSSocket) => void): this;
once(
event: "newSession",
listener: (sessionId: Buffer, sessionData: Buffer, callback: () => void) => void,
): this;
once(
event: "OCSPRequest",
listener: (
certificate: Buffer,
issuer: Buffer,
callback: (err: Error | null, resp: Buffer) => void,
) => void,
): this;
once(
event: "resumeSession",
listener: (sessionId: Buffer, callback: (err: Error | null, sessionData: Buffer | null) => void) => void,
): this;
once(event: "secureConnection", listener: (tlsSocket: TLSSocket) => void): this;
once(event: "keylog", listener: (line: Buffer, tlsSocket: TLSSocket) => void): this;
prependListener(event: string, listener: (...args: any[]) => void): this;
prependListener(event: "tlsClientError", listener: (err: Error, tlsSocket: TLSSocket) => void): this;
prependListener(
event: "newSession",
listener: (sessionId: Buffer, sessionData: Buffer, callback: () => void) => void,
): this;
prependListener(
event: "OCSPRequest",
listener: (
certificate: Buffer,
issuer: Buffer,
callback: (err: Error | null, resp: Buffer) => void,
) => void,
): this;
prependListener(
event: "resumeSession",
listener: (sessionId: Buffer, callback: (err: Error | null, sessionData: Buffer | null) => void) => void,
): this;
prependListener(event: "secureConnection", listener: (tlsSocket: TLSSocket) => void): this;
prependListener(event: "keylog", listener: (line: Buffer, tlsSocket: TLSSocket) => void): this;
prependOnceListener(event: string, listener: (...args: any[]) => void): this;
prependOnceListener(event: "tlsClientError", listener: (err: Error, tlsSocket: TLSSocket) => void): this;
prependOnceListener(
event: "newSession",
listener: (sessionId: Buffer, sessionData: Buffer, callback: () => void) => void,
): this;
prependOnceListener(
event: "OCSPRequest",
listener: (
certificate: Buffer,
issuer: Buffer,
callback: (err: Error | null, resp: Buffer) => void,
) => void,
): this;
prependOnceListener(
event: "resumeSession",
listener: (sessionId: Buffer, callback: (err: Error | null, sessionData: Buffer | null) => void) => void,
): this;
prependOnceListener(event: "secureConnection", listener: (tlsSocket: TLSSocket) => void): this;
prependOnceListener(event: "keylog", listener: (line: Buffer, tlsSocket: TLSSocket) => void): this;
}
/**
* @deprecated since v0.11.3 Use `tls.TLSSocket` instead.
*/
interface SecurePair {
encrypted: TLSSocket;
cleartext: TLSSocket;
}
type SecureVersion = "TLSv1.3" | "TLSv1.2" | "TLSv1.1" | "TLSv1";
interface SecureContextOptions {
/**
* If set, this will be called when a client opens a connection using the ALPN extension.
* One argument will be passed to the callback: an obj |
ect containing `servername` and `protocols` fields,
* respectively containing the server name from the SNI extension (if any) and an array of
* ALPN protocol name strings. The callback must return either one of the strings listed in `protocols`,
* which will be returned to the client as the selected ALPN protocol, or `undefined`,
* to reject the connection with a fatal alert. If a string is returned that does not match one of
* the client's ALPN protocols, an error will be thrown.
* This option cannot be used with the `ALPNProtocols` option, and setting both options will throw an error.
*/
ALPNCallback?: ((arg: { servername: string; protocols: string[] }) => string | undefined) | undefined;
/**
* Optionally override the trusted CA certificates. Default is to trust
* the well-known CAs curated by Mozilla. Mozilla's CAs are completely
* replaced when CAs are explicitly specified using this option.
*/
ca?: string | Buffer | Array<string | Buffer> | undefined;
/**
* Cert chains in PEM format. One cert chain should be provided per
* private key. Each cert chain should consist of the PEM formatted
* certificate for a provided private key, followed by the PEM
* formatted intermediate certificates (if any), in order, and not
* including the root CA (the root CA must be pre-known to the peer,
* see ca). When providing multiple cert chains, they do not have to
* be in the same order as their private keys in key. If the
* intermediate certificates are not provided, the peer will not be
* able to validate the certificate, and the handshake will fail.
*/
cert?: string | Buffer | Array<string | Buffer> | undefined;
/**
* Colon-separated list of supported signature algorithms. The list
* can contain digest algorithms (SHA256, MD5 etc.), public key
* algorithms (RSA-PSS, ECDSA etc.), combination of both (e.g
* 'RSA+SHA384') or TLS v1.3 scheme names (e.g. rsa_pss_pss_sha512).
*/
sigalgs?: string | undefined;
/**
* Cipher suite specification, replacing the default. For more
* information, see modifying the default cipher suite. Permitted
* ciphers can be obtained via tls.getCiphers(). Cipher names must be
* uppercased in order for OpenSSL to accept them.
*/
ciphers?: string | undefined;
/**
* Name of an OpenSSL engine which can provide the client certificate.
*/
clientCertEngine?: string | undefined;
/**
* PEM formatted CRLs (Certificate Revocation Lists).
*/
crl?: string | Buffer | Array<string | Buffer> | undefined;
/**
* `'auto'` or custom Diffie-Hellman parameters, required for non-ECDHE perfect forward secrecy.
* If omitted or invalid, the parameters are silently discarded and DHE ciphers will not be available.
* ECDHE-based perfect forward secrecy will still be available.
*/
dhparam?: string | Buffer | undefined;
/**
* A string describing a named curve or a colon separated list of curve
* NIDs or names, for example P-521:P-384:P-256, to use for ECDH key
* agreement. Set to auto to select the curve automatically. Use
* crypto.getCurves() to obtain a list of available curve names. On
* recent releases, openssl ecparam -list_curves will also display the
* name and description of each available elliptic curve. Default:
* tls.DEFAULT_ECDH_CURVE.
*/
ecdhCurve?: string | undefined;
/**
* Attempt to use the server's cipher suite preferences instead of the
* client's. When true, causes SSL_OP_CIPHER_SERVER_PREFERENCE to be
* set in secureOptions
|
*/
honorCipherOrder?: boolean | undefined;
/**
* Private keys in PEM format. PEM allows the option of private keys
* being encrypted. Encrypted keys will be decrypted with
* options.passphrase. Multiple keys using different algorithms can be
* provided either as an array of unencrypted key strings or buffers,
* or an array of objects in the form {pem: <string|buffer>[,
* passphrase: <string>]}. The object form can only occur in an array.
* object.passphrase is optional. Encrypted keys will be decrypted with
* object.passphrase if provided, or options.passphrase if it is not.
*/
key?: string | Buffer | Array<string | Buffer | KeyObject> | undefined;
/**
* Name of an OpenSSL engine to get private key from. Should be used
* together with privateKeyIdentifier.
*/
privateKeyEngine?: string | undefined;
/**
* Identifier of a private key managed by an OpenSSL engine. Should be
* used together with privateKeyEngine. Should not be set together with
* key, because both options define a private key in different ways.
*/
privateKeyIdentifier?: string | undefined;
/**
* Optionally set the maximum TLS version to allow. One
* of `'TLSv1.3'`, `'TLSv1.2'`, `'TLSv1.1'`, or `'TLSv1'`. Cannot be specified along with the
* `secureProtocol` option, use one or the other.
* **Default:** `'TLSv1.3'`, unless changed using CLI options. Using
* `--tls-max-v1.2` sets the default to `'TLSv1.2'`. Using `--tls-max-v1.3` sets the default to
* `'TLSv1.3'`. If multiple of the options are provided, the highest maximum is used.
*/
maxVersion?: SecureVersion | undefined;
/**
* Optionally set the minimum TLS version to allow. One
* of `'TLSv1.3'`, `'TLSv1.2'`, `'TLSv1.1'`, or `'TLSv1'`. Cannot be specified along with the
* `secureProtocol` option, use one or the other. It is not recommended to use
* less than TLSv1.2, but it may be required for interoperability.
* **Default:** `'TLSv1.2'`, unless changed using CLI options. Using
* `--tls-v1.0` sets the default to `'TLSv1'`. Using `--tls-v1.1` sets the default to
* `'TLSv1.1'`. Using `--tls-min-v1.3` sets the default to
* 'TLSv1.3'. If multiple of the options are provided, the lowest minimum is used.
*/
minVersion?: SecureVersion | undefined;
/**
* Shared passphrase used for a single private key and/or a PFX.
*/
passphrase?: string | undefined;
/**
* PFX or PKCS12 encoded private key and certificate chain. pfx is an
* alternative to providing key and cert individually. PFX is usually
* encrypted, if it is, passphrase will be used to decrypt it. Multiple
* PFX can be provided either as an array of unencrypted PFX buffers,
* or an array of objects in the form {buf: <string|buffer>[,
* passphrase: <string>]}. The object form can only occur in an array.
* object.passphrase is optional. Encrypted PFX will be decrypted with
* object.passphrase if provided, or options.passphrase if it is not.
*/
pfx?: string | Buffer | Array<string | Buffer | PxfObject> | undefined;
/**
* Optionally affect the OpenSSL protocol behavior, which is not
* usually necessary. This should be used carefully if at all! Value is
* a numeric bitmask of the SSL_OP_* options from OpenSSL Options
*/
secureOptions?: number | undefined; // Value is a numeric bitmask of the `SSL_OP_*` options
/**
* Legacy mechanism to select the TLS protocol version to use, it does
* not support independent control of the minimum and maximum version,
* and does not support limiting the |
protocol to TLSv1.3. Use
* minVersion and maxVersion instead. The possible values are listed as
* SSL_METHODS, use the function names as strings. For example, use
* 'TLSv1_1_method' to force TLS version 1.1, or 'TLS_method' to allow
* any TLS protocol version up to TLSv1.3. It is not recommended to use
* TLS versions less than 1.2, but it may be required for
* interoperability. Default: none, see minVersion.
*/
secureProtocol?: string | undefined;
/**
* Opaque identifier used by servers to ensure session state is not
* shared between applications. Unused by clients.
*/
sessionIdContext?: string | undefined;
/**
* 48-bytes of cryptographically strong pseudo-random data.
* See Session Resumption for more information.
*/
ticketKeys?: Buffer | undefined;
/**
* The number of seconds after which a TLS session created by the
* server will no longer be resumable. See Session Resumption for more
* information. Default: 300.
*/
sessionTimeout?: number | undefined;
}
interface SecureContext {
context: any;
}
/**
* Verifies the certificate `cert` is issued to `hostname`.
*
* Returns [Error](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Error) object, populating it with `reason`, `host`, and `cert` on
* failure. On success, returns [undefined](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Undefined_type).
*
* This function is intended to be used in combination with the`checkServerIdentity` option that can be passed to {@link connect} and as
* such operates on a `certificate object`. For other purposes, consider using `x509.checkHost()` instead.
*
* This function can be overwritten by providing an alternative function as the`options.checkServerIdentity` option that is passed to `tls.connect()`. The
* overwriting function can call `tls.checkServerIdentity()` of course, to augment
* the checks done with additional verification.
*
* This function is only called if the certificate passed all other checks, such as
* being issued by trusted CA (`options.ca`).
*
* Earlier versions of Node.js incorrectly accepted certificates for a given`hostname` if a matching `uniformResourceIdentifier` subject alternative name
* was present (see [CVE-2021-44531](https://cve.mitre.org/cgi-bin/cvename.cgi?name=CVE-2021-44531)). Applications that wish to accept`uniformResourceIdentifier` subject alternative names can use
* a custom`options.checkServerIdentity` function that implements the desired behavior.
* @since v0.8.4
* @param hostname The host name or IP address to verify the certificate against.
* @param cert A `certificate object` representing the peer's certificate.
*/
function checkServerIdentity(hostname: string, cert: PeerCertificate): Error | undefined;
/**
* Creates a new {@link Server}. The `secureConnectionListener`, if provided, is
* automatically set as a listener for the `'secureConnection'` event.
*
* The `ticketKeys` options is automatically shared between `node:cluster` module
* workers.
*
* The following illustrates a simple echo server:
*
* ```js
* const tls = require('node:tls');
* const fs = require('node:fs');
*
* const options = {
* key: fs.readFileSync('server-key.pem'),
* cert: fs.readFileSync('server-cert.pem'),
*
* // This is necessary only if using client certificate authentication.
* requestCert: true,
*
* // This is necessary only if the client uses a self-signed certificate.
* ca: [ fs.readFileSync('client-cert.pem') ],
* };
*
* const server = tls.createServer(options, (socket) => {
* conso |
le.log('server connected',
* socket.authorized ? 'authorized' : 'unauthorized');
* socket.write('welcome!\n');
* socket.setEncoding('utf8');
* socket.pipe(socket);
* });
* server.listen(8000, () => {
* console.log('server bound');
* });
* ```
*
* The server can be tested by connecting to it using the example client from {@link connect}.
* @since v0.3.2
*/
function createServer(secureConnectionListener?: (socket: TLSSocket) => void): Server;
function createServer(options: TlsOptions, secureConnectionListener?: (socket: TLSSocket) => void): Server;
/**
* The `callback` function, if specified, will be added as a listener for the `'secureConnect'` event.
*
* `tls.connect()` returns a {@link TLSSocket} object.
*
* Unlike the `https` API, `tls.connect()` does not enable the
* SNI (Server Name Indication) extension by default, which may cause some
* servers to return an incorrect certificate or reject the connection
* altogether. To enable SNI, set the `servername` option in addition
* to `host`.
*
* The following illustrates a client for the echo server example from {@link createServer}:
*
* ```js
* // Assumes an echo server that is listening on port 8000.
* const tls = require('node:tls');
* const fs = require('node:fs');
*
* const options = {
* // Necessary only if the server requires client certificate authentication.
* key: fs.readFileSync('client-key.pem'),
* cert: fs.readFileSync('client-cert.pem'),
*
* // Necessary only if the server uses a self-signed certificate.
* ca: [ fs.readFileSync('server-cert.pem') ],
*
* // Necessary only if the server's cert isn't for "localhost".
* checkServerIdentity: () => { return null; },
* };
*
* const socket = tls.connect(8000, options, () => {
* console.log('client connected',
* socket.authorized ? 'authorized' : 'unauthorized');
* process.stdin.pipe(socket);
* process.stdin.resume();
* });
* socket.setEncoding('utf8');
* socket.on('data', (data) => {
* console.log(data);
* });
* socket.on('end', () => {
* console.log('server ends connection');
* });
* ```
* @since v0.11.3
*/
function connect(options: ConnectionOptions, secureConnectListener?: () => void): TLSSocket;
function connect(
port: number,
host?: string,
options?: ConnectionOptions,
secureConnectListener?: () => void,
): TLSSocket;
function connect(port: number, options?: ConnectionOptions, secureConnectListener?: () => void): TLSSocket;
/**
* Creates a new secure pair object with two streams, one of which reads and writes
* the encrypted data and the other of which reads and writes the cleartext data.
* Generally, the encrypted stream is piped to/from an incoming encrypted data
* stream and the cleartext one is used as a replacement for the initial encrypted
* stream.
*
* `tls.createSecurePair()` returns a `tls.SecurePair` object with `cleartext` and`encrypted` stream properties.
*
* Using `cleartext` has the same API as {@link TLSSocket}.
*
* The `tls.createSecurePair()` method is now deprecated in favor of`tls.TLSSocket()`. For example, the code:
*
* ```js
* pair = tls.createSecurePair(// ... );
* pair.encrypted.pipe(socket);
* socket.pipe(pair.encrypted);
* ```
*
* can be replaced by:
*
* ```js
* secureSocket = tls.TLSSocket(socket, options);
* ```
*
* where `secureSocket` has the same API as `pair.cleartext`.
* @since v0.3.2
* @deprecated Since v0.11.3 - Use {@link TLSSocket} instead.
* @param context A secure context object as returned by `tls.createSecureContext()`
* @param is |
Server `true` to specify that this TLS connection should be opened as a server.
* @param requestCert `true` to specify whether a server should request a certificate from a connecting client. Only applies when `isServer` is `true`.
* @param rejectUnauthorized If not `false` a server automatically reject clients with invalid certificates. Only applies when `isServer` is `true`.
*/
function createSecurePair(
context?: SecureContext,
isServer?: boolean,
requestCert?: boolean,
rejectUnauthorized?: boolean,
): SecurePair;
/**
* {@link createServer} sets the default value of the `honorCipherOrder` option
* to `true`, other APIs that create secure contexts leave it unset.
*
* {@link createServer} uses a 128 bit truncated SHA1 hash value generated
* from `process.argv` as the default value of the `sessionIdContext` option, other
* APIs that create secure contexts have no default value.
*
* The `tls.createSecureContext()` method creates a `SecureContext` object. It is
* usable as an argument to several `tls` APIs, such as `server.addContext()`,
* but has no public methods. The {@link Server} constructor and the {@link createServer} method do not support the `secureContext` option.
*
* A key is _required_ for ciphers that use certificates. Either `key` or`pfx` can be used to provide it.
*
* If the `ca` option is not given, then Node.js will default to using [Mozilla's publicly trusted list of
* CAs](https://hg.mozilla.org/mozilla-central/raw-file/tip/security/nss/lib/ckfw/builtins/certdata.txt).
*
* Custom DHE parameters are discouraged in favor of the new `dhparam: 'auto'`option. When set to `'auto'`, well-known DHE parameters of sufficient strength
* will be selected automatically. Otherwise, if necessary, `openssl dhparam` can
* be used to create custom parameters. The key length must be greater than or
* equal to 1024 bits or else an error will be thrown. Although 1024 bits is
* permissible, use 2048 bits or larger for stronger security.
* @since v0.11.13
*/
function createSecureContext(options?: SecureContextOptions): SecureContext;
/**
* Returns an array with the names of the supported TLS ciphers. The names are
* lower-case for historical reasons, but must be uppercased to be used in
* the `ciphers` option of {@link createSecureContext}.
*
* Not all supported ciphers are enabled by default. See `Modifying the default TLS cipher suite`.
*
* Cipher names that start with `'tls_'` are for TLSv1.3, all the others are for
* TLSv1.2 and below.
*
* ```js
* console.log(tls.getCiphers()); // ['aes128-gcm-sha256', 'aes128-sha', ...]
* ```
* @since v0.10.2
*/
function getCiphers(): string[];
/**
* The default curve name to use for ECDH key agreement in a tls server.
* The default value is 'auto'. See tls.createSecureContext() for further
* information.
*/
let DEFAULT_ECDH_CURVE: string;
/**
* The default value of the maxVersion option of
* tls.createSecureContext(). It can be assigned any of the supported TLS
* protocol versions, 'TLSv1.3', 'TLSv1.2', 'TLSv1.1', or 'TLSv1'. Default:
* 'TLSv1.3', unless changed using CLI options. Using --tls-max-v1.2 sets
* the default to 'TLSv1.2'. Using --tls-max-v1.3 sets the default to
* 'TLSv1.3'. If multiple of the options are provided, the highest maximum
* is used.
*/
let DEFAULT_MAX_VERSION: SecureVersion;
/**
* The default value of the minVersion option of tls.createSecureContext().
* It can be assigned any of the supported TLS protocol versions,
* 'TLSv1.3', 'TLSv1.2', 'TLSv1.1', or 'TLSv1'. Default: 'TLSv1.2', unless
* changed using CLI options. Using --tls-min-v1.0 sets the default to
* 'TLSv1'. Using --tls-min-v1.1 sets the default to 'TLSv1. |
1'. Using
* --tls-min-v1.3 sets the default to 'TLSv1.3'. If multiple of the options
* are provided, the lowest minimum is used.
*/
let DEFAULT_MIN_VERSION: SecureVersion;
/**
* The default value of the ciphers option of tls.createSecureContext().
* It can be assigned any of the supported OpenSSL ciphers.
* Defaults to the content of crypto.constants.defaultCoreCipherList, unless
* changed using CLI options using --tls-default-ciphers.
*/
let DEFAULT_CIPHERS: string;
/**
* An immutable array of strings representing the root certificates (in PEM
* format) used for verifying peer certificates. This is the default value
* of the ca option to tls.createSecureContext().
*/
const rootCertificates: readonly string[];
}
declare module "node:tls" {
export * from "tls";
}
|
/**
* The `node:readline` module provides an interface for reading data from a `Readable` stream (such as `process.stdin`) one line at a time.
*
* To use the promise-based APIs:
*
* ```js
* import * as readline from 'node:readline/promises';
* ```
*
* To use the callback and sync APIs:
*
* ```js
* import * as readline from 'node:readline';
* ```
*
* The following simple example illustrates the basic use of the `node:readline`module.
*
* ```js
* import * as readline from 'node:readline/promises';
* import { stdin as input, stdout as output } from 'node:process';
*
* const rl = readline.createInterface({ input, output });
*
* const answer = await rl.question('What do you think of Node.js? ');
*
* console.log(`Thank you for your valuable feedback: ${answer}`);
*
* rl.close();
* ```
*
* Once this code is invoked, the Node.js application will not terminate until the`readline.Interface` is closed because the interface waits for data to be
* received on the `input` stream.
* @see [source](https://github.com/nodejs/node/blob/v20.2.0/lib/readline.js)
*/
declare module "readline" {
import { Abortable, EventEmitter } from "node:events";
import * as promises from "node:readline/promises";
export { promises };
export interface Key {
sequence?: string | undefined;
name?: string | undefined;
ctrl?: boolean | undefined;
meta?: boolean | undefined;
shift?: boolean | undefined;
}
/**
* Instances of the `readline.Interface` class are constructed using the`readline.createInterface()` method. Every instance is associated with a
* single `input` `Readable` stream and a single `output` `Writable` stream.
* The `output` stream is used to print prompts for user input that arrives on,
* and is read from, the `input` stream.
* @since v0.1.104
*/
export class Interface extends EventEmitter {
readonly terminal: boolean;
/**
* The current input data being processed by node.
*
* This can be used when collecting input from a TTY stream to retrieve the
* current value that has been processed thus far, prior to the `line` event
* being emitted. Once the `line` event has been emitted, this property will
* be an empty string.
*
* Be aware that modifying the value during the instance runtime may have
* unintended consequences if `rl.cursor` is not also controlled.
*
* **If not using a TTY stream for input, use the `'line'` event.**
*
* One possible use case would be as follows:
*
* ```js
* const values = ['lorem ipsum', 'dolor sit amet'];
* const rl = readline.createInterface(process.stdin);
* const showResults = debounce(() => {
* console.log(
* '\n',
* values.filter((val) => val.startsWith(rl.line)).join(' '),
* );
* }, 300);
* process.stdin.on('keypress', (c, k) => {
* showResults();
* });
* ```
* @since v0.1.98
*/
readonly line: string;
/**
* The cursor position relative to `rl.line`.
*
* This will track where the current cursor lands in the input string, when
* reading input from a TTY stream. The position of cursor determines the
* portion of the input string that will be modified as input is processed,
* as well as the column where the terminal caret will be rendered.
* @since v0.1.98
*/
readonly cursor: number;
/**
* NOTE: According to the documentation:
*
* > Instances of the `readline.Interface` class are constructed using the
* > `readline.createInterface()` method.
*
* @see https://nodejs.org/dist/latest-v20.x/docs/api/readline.html#class-interfaceconstructor
*/
pro |
tected constructor(
input: NodeJS.ReadableStream,
output?: NodeJS.WritableStream,
completer?: Completer | AsyncCompleter,
terminal?: boolean,
);
/**
* NOTE: According to the documentation:
*
* > Instances of the `readline.Interface` class are constructed using the
* > `readline.createInterface()` method.
*
* @see https://nodejs.org/dist/latest-v20.x/docs/api/readline.html#class-interfaceconstructor
*/
protected constructor(options: ReadLineOptions);
/**
* The `rl.getPrompt()` method returns the current prompt used by `rl.prompt()`.
* @since v15.3.0, v14.17.0
* @return the current prompt string
*/
getPrompt(): string;
/**
* The `rl.setPrompt()` method sets the prompt that will be written to `output`whenever `rl.prompt()` is called.
* @since v0.1.98
*/
setPrompt(prompt: string): void;
/**
* The `rl.prompt()` method writes the `Interface` instances configured`prompt` to a new line in `output` in order to provide a user with a new
* location at which to provide input.
*
* When called, `rl.prompt()` will resume the `input` stream if it has been
* paused.
*
* If the `Interface` was created with `output` set to `null` or`undefined` the prompt is not written.
* @since v0.1.98
* @param preserveCursor If `true`, prevents the cursor placement from being reset to `0`.
*/
prompt(preserveCursor?: boolean): void;
/**
* The `rl.question()` method displays the `query` by writing it to the `output`,
* waits for user input to be provided on `input`, then invokes the `callback`function passing the provided input as the first argument.
*
* When called, `rl.question()` will resume the `input` stream if it has been
* paused.
*
* If the `Interface` was created with `output` set to `null` or`undefined` the `query` is not written.
*
* The `callback` function passed to `rl.question()` does not follow the typical
* pattern of accepting an `Error` object or `null` as the first argument.
* The `callback` is called with the provided answer as the only argument.
*
* An error will be thrown if calling `rl.question()` after `rl.close()`.
*
* Example usage:
*
* ```js
* rl.question('What is your favorite food? ', (answer) => {
* console.log(`Oh, so your favorite food is ${answer}`);
* });
* ```
*
* Using an `AbortController` to cancel a question.
*
* ```js
* const ac = new AbortController();
* const signal = ac.signal;
*
* rl.question('What is your favorite food? ', { signal }, (answer) => {
* console.log(`Oh, so your favorite food is ${answer}`);
* });
*
* signal.addEventListener('abort', () => {
* console.log('The food question timed out');
* }, { once: true });
*
* setTimeout(() => ac.abort(), 10000);
* ```
* @since v0.3.3
* @param query A statement or query to write to `output`, prepended to the prompt.
* @param callback A callback function that is invoked with the user's input in response to the `query`.
*/
question(query: string, callback: (answer: string) => void): void;
question(query: string, options: Abortable, callback: (answer: string) => void): void;
/**
* The `rl.pause()` method pauses the `input` stream, allowing it to be resumed
* later if necessary.
*
* Calling `rl.pause()` does not immediately pause other events (including`'line'`) from being emitted by the `Interface` in |
stance.
* @since v0.3.4
*/
pause(): this;
/**
* The `rl.resume()` method resumes the `input` stream if it has been paused.
* @since v0.3.4
*/
resume(): this;
/**
* The `rl.close()` method closes the `Interface` instance and
* relinquishes control over the `input` and `output` streams. When called,
* the `'close'` event will be emitted.
*
* Calling `rl.close()` does not immediately stop other events (including `'line'`)
* from being emitted by the `Interface` instance.
* @since v0.1.98
*/
close(): void;
/**
* The `rl.write()` method will write either `data` or a key sequence identified
* by `key` to the `output`. The `key` argument is supported only if `output` is
* a `TTY` text terminal. See `TTY keybindings` for a list of key
* combinations.
*
* If `key` is specified, `data` is ignored.
*
* When called, `rl.write()` will resume the `input` stream if it has been
* paused.
*
* If the `Interface` was created with `output` set to `null` or`undefined` the `data` and `key` are not written.
*
* ```js
* rl.write('Delete this!');
* // Simulate Ctrl+U to delete the line written previously
* rl.write(null, { ctrl: true, name: 'u' });
* ```
*
* The `rl.write()` method will write the data to the `readline` `Interface`'s`input`_as if it were provided by the user_.
* @since v0.1.98
*/
write(data: string | Buffer, key?: Key): void;
write(data: undefined | null | string | Buffer, key: Key): void;
/**
* Returns the real position of the cursor in relation to the input
* prompt + string. Long input (wrapping) strings, as well as multiple
* line prompts are included in the calculations.
* @since v13.5.0, v12.16.0
*/
getCursorPos(): CursorPos;
/**
* events.EventEmitter
* 1. close
* 2. line
* 3. pause
* 4. resume
* 5. SIGCONT
* 6. SIGINT
* 7. SIGTSTP
* 8. history
*/
addListener(event: string, listener: (...args: any[]) => void): this;
addListener(event: "close", listener: () => void): this;
addListener(event: "line", listener: (input: string) => void): this;
addListener(event: "pause", listener: () => void): this;
addListener(event: "resume", listener: () => void): this;
addListener(event: "SIGCONT", listener: () => void): this;
addListener(event: "SIGINT", listener: () => void): this;
addListener(event: "SIGTSTP", listener: () => void): this;
addListener(event: "history", listener: (history: string[]) => void): this;
emit(event: string | symbol, ...args: any[]): boolean;
emit(event: "close"): boolean;
emit(event: "line", input: string): boolean;
emit(event: "pause"): boolean;
emit(event: "resume"): boolean;
emit(event: "SIGCONT"): boolean;
emit(event: "SIGINT"): boolean;
emit(event: "SIGTSTP"): boolean;
emit(event: "history", history: string[]): boolean;
on(event: string, listener: (...args: any[]) => void): this;
on(event: "close", listener: () => void): this;
on(event: "line", listener: (input: string) => void): this;
on(event: "pause", listener: () => void): this;
on(event: "resume", listener: () => void): this;
on(event: "SIGCONT", listener: () => void): this;
on(event: "SIGINT", listener: () => void): this;
on(event: "SIGTSTP", listener: () => void): this;
on(event: "history", listener: (history: string[]) => void): this;
once(event: string, listener: (...args: any[]) => void): this;
once(event: |
"close", listener: () => void): this;
once(event: "line", listener: (input: string) => void): this;
once(event: "pause", listener: () => void): this;
once(event: "resume", listener: () => void): this;
once(event: "SIGCONT", listener: () => void): this;
once(event: "SIGINT", listener: () => void): this;
once(event: "SIGTSTP", listener: () => void): this;
once(event: "history", listener: (history: string[]) => void): this;
prependListener(event: string, listener: (...args: any[]) => void): this;
prependListener(event: "close", listener: () => void): this;
prependListener(event: "line", listener: (input: string) => void): this;
prependListener(event: "pause", listener: () => void): this;
prependListener(event: "resume", listener: () => void): this;
prependListener(event: "SIGCONT", listener: () => void): this;
prependListener(event: "SIGINT", listener: () => void): this;
prependListener(event: "SIGTSTP", listener: () => void): this;
prependListener(event: "history", listener: (history: string[]) => void): this;
prependOnceListener(event: string, listener: (...args: any[]) => void): this;
prependOnceListener(event: "close", listener: () => void): this;
prependOnceListener(event: "line", listener: (input: string) => void): this;
prependOnceListener(event: "pause", listener: () => void): this;
prependOnceListener(event: "resume", listener: () => void): this;
prependOnceListener(event: "SIGCONT", listener: () => void): this;
prependOnceListener(event: "SIGINT", listener: () => void): this;
prependOnceListener(event: "SIGTSTP", listener: () => void): this;
prependOnceListener(event: "history", listener: (history: string[]) => void): this;
[Symbol.asyncIterator](): AsyncIterableIterator<string>;
}
export type ReadLine = Interface; // type forwarded for backwards compatibility
export type Completer = (line: string) => CompleterResult;
export type AsyncCompleter = (
line: string,
callback: (err?: null | Error, result?: CompleterResult) => void,
) => void;
export type CompleterResult = [string[], string];
export interface ReadLineOptions {
input: NodeJS.ReadableStream;
output?: NodeJS.WritableStream | undefined;
completer?: Completer | AsyncCompleter | undefined;
terminal?: boolean | undefined;
/**
* Initial list of history lines. This option makes sense
* only if `terminal` is set to `true` by the user or by an internal `output`
* check, otherwise the history caching mechanism is not initialized at all.
* @default []
*/
history?: string[] | undefined;
historySize?: number | undefined;
prompt?: string | undefined;
crlfDelay?: number | undefined;
/**
* If `true`, when a new input line added
* to the history list duplicates an older one, this removes the older line
* from the list.
* @default false
*/
removeHistoryDuplicates?: boolean | undefined;
escapeCodeTimeout?: number | undefined;
tabSize?: number | undefined;
}
/**
* The `readline.createInterface()` method creates a new `readline.Interface`instance.
*
* ```js
* const readline = require('node:readline');
* const rl = readline.createInterface({
* input: process.stdin,
* output: process.stdout,
* });
* ```
*
* Once the `readline.Interface` instance is created, the most common case is to
* listen for the `'line'` event:
*
* ```js
* rl.on('line', (line) => {
* console.log(`Received: ${line}`);
* });
* ```
*
* If `terminal` is `true` for this instance then the `output` stream will get
* the best compatibility if it defines an `output. |
columns` property and emits
* a `'resize'` event on the `output` if or when the columns ever change
* (`process.stdout` does this automatically when it is a TTY).
*
* When creating a `readline.Interface` using `stdin` as input, the program
* will not terminate until it receives an [EOF character](https://en.wikipedia.org/wiki/End-of-file#EOF_character). To exit without
* waiting for user input, call `process.stdin.unref()`.
* @since v0.1.98
*/
export function createInterface(
input: NodeJS.ReadableStream,
output?: NodeJS.WritableStream,
completer?: Completer | AsyncCompleter,
terminal?: boolean,
): Interface;
export function createInterface(options: ReadLineOptions): Interface;
/**
* The `readline.emitKeypressEvents()` method causes the given `Readable` stream to begin emitting `'keypress'` events corresponding to received input.
*
* Optionally, `interface` specifies a `readline.Interface` instance for which
* autocompletion is disabled when copy-pasted input is detected.
*
* If the `stream` is a `TTY`, then it must be in raw mode.
*
* This is automatically called by any readline instance on its `input` if the`input` is a terminal. Closing the `readline` instance does not stop
* the `input` from emitting `'keypress'` events.
*
* ```js
* readline.emitKeypressEvents(process.stdin);
* if (process.stdin.isTTY)
* process.stdin.setRawMode(true);
* ```
*
* ## Example: Tiny CLI
*
* The following example illustrates the use of `readline.Interface` class to
* implement a small command-line interface:
*
* ```js
* const readline = require('node:readline');
* const rl = readline.createInterface({
* input: process.stdin,
* output: process.stdout,
* prompt: 'OHAI> ',
* });
*
* rl.prompt();
*
* rl.on('line', (line) => {
* switch (line.trim()) {
* case 'hello':
* console.log('world!');
* break;
* default:
* console.log(`Say what? I might have heard '${line.trim()}'`);
* break;
* }
* rl.prompt();
* }).on('close', () => {
* console.log('Have a great day!');
* process.exit(0);
* });
* ```
*
* ## Example: Read file stream line-by-Line
*
* A common use case for `readline` is to consume an input file one line at a
* time. The easiest way to do so is leveraging the `fs.ReadStream` API as
* well as a `for await...of` loop:
*
* ```js
* const fs = require('node:fs');
* const readline = require('node:readline');
*
* async function processLineByLine() {
* const fileStream = fs.createReadStream('input.txt');
*
* const rl = readline.createInterface({
* input: fileStream,
* crlfDelay: Infinity,
* });
* // Note: we use the crlfDelay option to recognize all instances of CR LF
* // ('\r\n') in input.txt as a single line break.
*
* for await (const line of rl) {
* // Each line in input.txt will be successively available here as `line`.
* console.log(`Line from file: ${line}`);
* }
* }
*
* processLineByLine();
* ```
*
* Alternatively, one could use the `'line'` event:
*
* ```js
* const fs = require('node:fs');
* const readline = require('node:readline');
*
* const rl = readline.createInterface({
* input: fs.createReadStream('sample.txt'),
* crlfDelay: Infinity,
* });
*
* rl.on('line', (line) => {
* console.log(`Line from file: ${line}`);
* });
* ```
*
* Currently, `for await...of` loop can be a bit slower. If `async` / `await`flow and speed are both essential, a mixed approach can be applied:
*
* ```js
* const { once } = |
require('node:events');
* const { createReadStream } = require('node:fs');
* const { createInterface } = require('node:readline');
*
* (async function processLineByLine() {
* try {
* const rl = createInterface({
* input: createReadStream('big-file.txt'),
* crlfDelay: Infinity,
* });
*
* rl.on('line', (line) => {
* // Process the line.
* });
*
* await once(rl, 'close');
*
* console.log('File processed.');
* } catch (err) {
* console.error(err);
* }
* })();
* ```
* @since v0.7.7
*/
export function emitKeypressEvents(stream: NodeJS.ReadableStream, readlineInterface?: Interface): void;
export type Direction = -1 | 0 | 1;
export interface CursorPos {
rows: number;
cols: number;
}
/**
* The `readline.clearLine()` method clears current line of given `TTY` stream
* in a specified direction identified by `dir`.
* @since v0.7.7
* @param callback Invoked once the operation completes.
* @return `false` if `stream` wishes for the calling code to wait for the `'drain'` event to be emitted before continuing to write additional data; otherwise `true`.
*/
export function clearLine(stream: NodeJS.WritableStream, dir: Direction, callback?: () => void): boolean;
/**
* The `readline.clearScreenDown()` method clears the given `TTY` stream from
* the current position of the cursor down.
* @since v0.7.7
* @param callback Invoked once the operation completes.
* @return `false` if `stream` wishes for the calling code to wait for the `'drain'` event to be emitted before continuing to write additional data; otherwise `true`.
*/
export function clearScreenDown(stream: NodeJS.WritableStream, callback?: () => void): boolean;
/**
* The `readline.cursorTo()` method moves cursor to the specified position in a
* given `TTY` `stream`.
* @since v0.7.7
* @param callback Invoked once the operation completes.
* @return `false` if `stream` wishes for the calling code to wait for the `'drain'` event to be emitted before continuing to write additional data; otherwise `true`.
*/
export function cursorTo(stream: NodeJS.WritableStream, x: number, y?: number, callback?: () => void): boolean;
/**
* The `readline.moveCursor()` method moves the cursor _relative_ to its current
* position in a given `TTY` `stream`.
* @since v0.7.7
* @param callback Invoked once the operation completes.
* @return `false` if `stream` wishes for the calling code to wait for the `'drain'` event to be emitted before continuing to write additional data; otherwise `true`.
*/
export function moveCursor(stream: NodeJS.WritableStream, dx: number, dy: number, callback?: () => void): boolean;
}
declare module "node:readline" {
export * from "readline";
}
|
/**
* The `node:trace_events` module provides a mechanism to centralize tracing
* information generated by V8, Node.js core, and userspace code.
*
* Tracing can be enabled with the `--trace-event-categories` command-line flag
* or by using the `node:trace_events` module. The `--trace-event-categories` flag
* accepts a list of comma-separated category names.
*
* The available categories are:
*
* * `node`: An empty placeholder.
* * `node.async_hooks`: Enables capture of detailed `async_hooks` trace data.
* The `async_hooks` events have a unique `asyncId` and a special `triggerId` `triggerAsyncId` property.
* * `node.bootstrap`: Enables capture of Node.js bootstrap milestones.
* * `node.console`: Enables capture of `console.time()` and `console.count()`output.
* * `node.threadpoolwork.sync`: Enables capture of trace data for threadpool
* synchronous operations, such as `blob`, `zlib`, `crypto` and `node_api`.
* * `node.threadpoolwork.async`: Enables capture of trace data for threadpool
* asynchronous operations, such as `blob`, `zlib`, `crypto` and `node_api`.
* * `node.dns.native`: Enables capture of trace data for DNS queries.
* * `node.net.native`: Enables capture of trace data for network.
* * `node.environment`: Enables capture of Node.js Environment milestones.
* * `node.fs.sync`: Enables capture of trace data for file system sync methods.
* * `node.fs_dir.sync`: Enables capture of trace data for file system sync
* directory methods.
* * `node.fs.async`: Enables capture of trace data for file system async methods.
* * `node.fs_dir.async`: Enables capture of trace data for file system async
* directory methods.
* * `node.perf`: Enables capture of `Performance API` measurements.
* * `node.perf.usertiming`: Enables capture of only Performance API User Timing
* measures and marks.
* * `node.perf.timerify`: Enables capture of only Performance API timerify
* measurements.
* * `node.promises.rejections`: Enables capture of trace data tracking the number
* of unhandled Promise rejections and handled-after-rejections.
* * `node.vm.script`: Enables capture of trace data for the `node:vm` module's`runInNewContext()`, `runInContext()`, and `runInThisContext()` methods.
* * `v8`: The `V8` events are GC, compiling, and execution related.
* * `node.http`: Enables capture of trace data for http request / response.
*
* By default the `node`, `node.async_hooks`, and `v8` categories are enabled.
*
* ```bash
* node --trace-event-categories v8,node,node.async_hooks server.js
* ```
*
* Prior versions of Node.js required the use of the `--trace-events-enabled`flag to enable trace events. This requirement has been removed. However, the`--trace-events-enabled` flag _may_ still be
* used and will enable the`node`, `node.async_hooks`, and `v8` trace event categories by default.
*
* ```bash
* node --trace-events-enabled
*
* # is equivalent to
*
* node --trace-event-categories v8,node,node.async_hooks
* ```
*
* Alternatively, trace events may be enabled using the `node:trace_events` module:
*
* ```js
* const trace_events = require('node:trace_events');
* const tracing = trace_events.createTracing({ categories: ['node.perf'] });
* tracing.enable(); // Enable trace event capture for the 'node.perf' category
*
* // do work
*
* tracing.disable(); // Disable trace event capture for the 'node.perf' category
* ```
*
* Running Node.js with tracing enabled will produce log files that can be opened
* in the [`chrome://tracing`](https://www.chromium.org/developers/how-tos/trace-event-profiling-tool) tab of Chrome.
*
* The logging file is by default called `node_trace.${rotation}.log`, where`${rotation}` is an incrementing log-rotation id. The filepath pattern can
* be specified with `--trace-event-file-pattern` that accepts a template
* string that supports `${rotation}` and `${pid}`:
*
* ```bash
* node --trace-event-categories v8 --trace-event-file-pattern '${pid}-${rotatio |
n}.log' server.js
* ```
*
* To guarantee that the log file is properly generated after signal events like`SIGINT`, `SIGTERM`, or `SIGBREAK`, make sure to have the appropriate handlers
* in your code, such as:
*
* ```js
* process.on('SIGINT', function onSigint() {
* console.info('Received SIGINT.');
* process.exit(130); // Or applicable exit code depending on OS and signal
* });
* ```
*
* The tracing system uses the same time source
* as the one used by `process.hrtime()`.
* However the trace-event timestamps are expressed in microseconds,
* unlike `process.hrtime()` which returns nanoseconds.
*
* The features from this module are not available in `Worker` threads.
* @experimental
* @see [source](https://github.com/nodejs/node/blob/v20.2.0/lib/trace_events.js)
*/
declare module "trace_events" {
/**
* The `Tracing` object is used to enable or disable tracing for sets of
* categories. Instances are created using the
* `trace_events.createTracing()` method.
*
* When created, the `Tracing` object is disabled. Calling the
* `tracing.enable()` method adds the categories to the set of enabled trace
* event categories. Calling `tracing.disable()` will remove the categories
* from the set of enabled trace event categories.
*/
interface Tracing {
/**
* A comma-separated list of the trace event categories covered by this
* `Tracing` object.
*/
readonly categories: string;
/**
* Disables this `Tracing` object.
*
* Only trace event categories _not_ covered by other enabled `Tracing`
* objects and _not_ specified by the `--trace-event-categories` flag
* will be disabled.
*/
disable(): void;
/**
* Enables this `Tracing` object for the set of categories covered by
* the `Tracing` object.
*/
enable(): void;
/**
* `true` only if the `Tracing` object has been enabled.
*/
readonly enabled: boolean;
}
interface CreateTracingOptions {
/**
* An array of trace category names. Values included in the array are
* coerced to a string when possible. An error will be thrown if the
* value cannot be coerced.
*/
categories: string[];
}
/**
* Creates and returns a `Tracing` object for the given set of `categories`.
*
* ```js
* const trace_events = require('node:trace_events');
* const categories = ['node.perf', 'node.async_hooks'];
* const tracing = trace_events.createTracing({ categories });
* tracing.enable();
* // do stuff
* tracing.disable();
* ```
* @since v10.0.0
* @return .
*/
function createTracing(options: CreateTracingOptions): Tracing;
/**
* Returns a comma-separated list of all currently-enabled trace event
* categories. The current set of enabled trace event categories is determined
* by the _union_ of all currently-enabled `Tracing` objects and any categories
* enabled using the `--trace-event-categories` flag.
*
* Given the file `test.js` below, the command`node --trace-event-categories node.perf test.js` will print`'node.async_hooks,node.perf'` to the console.
*
* ```js
* const trace_events = require('node:trace_events');
* const t1 = trace_events.createTracing({ categories: ['node.async_hooks'] });
* const t2 = trace_events.createTracing({ categories: ['node.perf'] });
* const t3 = trace_events.createTracing({ categories: ['v8'] });
*
* t1.enable();
* t2.enable();
*
* console.log(trace_events.getEnabledCategories());
* ```
* @since v10.0.0
*/
function getEnabledCategories(): string | undefined;
}
declare module "node:trace_events" {
export * from "trace_events";
}
|
/**
* Much of the Node.js core API is built around an idiomatic asynchronous
* event-driven architecture in which certain kinds of objects (called "emitters")
* emit named events that cause `Function` objects ("listeners") to be called.
*
* For instance: a `net.Server` object emits an event each time a peer
* connects to it; a `fs.ReadStream` emits an event when the file is opened;
* a `stream` emits an event whenever data is available to be read.
*
* All objects that emit events are instances of the `EventEmitter` class. These
* objects expose an `eventEmitter.on()` function that allows one or more
* functions to be attached to named events emitted by the object. Typically,
* event names are camel-cased strings but any valid JavaScript property key
* can be used.
*
* When the `EventEmitter` object emits an event, all of the functions attached
* to that specific event are called _synchronously_. Any values returned by the
* called listeners are _ignored_ and discarded.
*
* The following example shows a simple `EventEmitter` instance with a single
* listener. The `eventEmitter.on()` method is used to register listeners, while
* the `eventEmitter.emit()` method is used to trigger the event.
*
* ```js
* import { EventEmitter } from 'node:events';
*
* class MyEmitter extends EventEmitter {}
*
* const myEmitter = new MyEmitter();
* myEmitter.on('event', () => {
* console.log('an event occurred!');
* });
* myEmitter.emit('event');
* ```
* @see [source](https://github.com/nodejs/node/blob/v20.2.0/lib/events.js)
*/
declare module "events" {
import { AsyncResource, AsyncResourceOptions } from "node:async_hooks";
// NOTE: This class is in the docs but is **not actually exported** by Node.
// If https://github.com/nodejs/node/issues/39903 gets resolved and Node
// actually starts exporting the class, uncomment below.
// import { EventListener, EventListenerObject } from '__dom-events';
// /** The NodeEventTarget is a Node.js-specific extension to EventTarget that emulates a subset of the EventEmitter API. */
// interface NodeEventTarget extends EventTarget {
// /**
// * Node.js-specific extension to the `EventTarget` class that emulates the equivalent `EventEmitter` API.
// * The only difference between `addListener()` and `addEventListener()` is that addListener() will return a reference to the EventTarget.
// */
// addListener(type: string, listener: EventListener | EventListenerObject, options?: { once: boolean }): this;
// /** Node.js-specific extension to the `EventTarget` class that returns an array of event `type` names for which event listeners are registered. */
// eventNames(): string[];
// /** Node.js-specific extension to the `EventTarget` class that returns the number of event listeners registered for the `type`. */
// listenerCount(type: string): number;
// /** Node.js-specific alias for `eventTarget.removeListener()`. */
// off(type: string, listener: EventListener | EventListenerObject): this;
// /** Node.js-specific alias for `eventTarget.addListener()`. */
// on(type: string, listener: EventListener | EventListenerObject, options?: { once: boolean }): this;
// /** Node.js-specific extension to the `EventTarget` class that adds a `once` listener for the given event `type`. This is equivalent to calling `on` with the `once` option set to `true`. */
// once(type: string, listener: EventListener | EventListenerObject): this;
// /**
// * Node.js-specific extension to the `EventTarget` class.
// * If `type` is specified, removes all registered listeners for `type`,
// * otherwise removes all registered listeners.
// */
// removeAllListeners(type: string): this;
// /**
// * Node.js-specific extension to the `EventTarget` class that removes the listener for the given `type`.
|
// * The only difference between `removeListener()` and `removeEventListener()` is that `removeListener()` will return a reference to the `EventTarget`.
// */
// removeListener(type: string, listener: EventListener | EventListenerObject): this;
// }
interface EventEmitterOptions {
/**
* Enables automatic capturing of promise rejection.
*/
captureRejections?: boolean | undefined;
}
// Any EventTarget with a Node-style `once` function
interface _NodeEventTarget {
once(eventName: string | symbol, listener: (...args: any[]) => void): this;
}
// Any EventTarget with a DOM-style `addEventListener`
interface _DOMEventTarget {
addEventListener(
eventName: string,
listener: (...args: any[]) => void,
opts?: {
once: boolean;
},
): any;
}
interface StaticEventEmitterOptions {
signal?: AbortSignal | undefined;
}
interface EventEmitter extends NodeJS.EventEmitter {}
/**
* The `EventEmitter` class is defined and exposed by the `node:events` module:
*
* ```js
* import { EventEmitter } from 'node:events';
* ```
*
* All `EventEmitter`s emit the event `'newListener'` when new listeners are
* added and `'removeListener'` when existing listeners are removed.
*
* It supports the following option:
* @since v0.1.26
*/
class EventEmitter {
constructor(options?: EventEmitterOptions);
[EventEmitter.captureRejectionSymbol]?(error: Error, event: string, ...args: any[]): void;
/**
* Creates a `Promise` that is fulfilled when the `EventEmitter` emits the given
* event or that is rejected if the `EventEmitter` emits `'error'` while waiting.
* The `Promise` will resolve with an array of all the arguments emitted to the
* given event.
*
* This method is intentionally generic and works with the web platform [EventTarget](https://dom.spec.whatwg.org/#interface-eventtarget) interface, which has no special`'error'` event
* semantics and does not listen to the `'error'` event.
*
* ```js
* import { once, EventEmitter } from 'node:events';
* import process from 'node:process';
*
* const ee = new EventEmitter();
*
* process.nextTick(() => {
* ee.emit('myevent', 42);
* });
*
* const [value] = await once(ee, 'myevent');
* console.log(value);
*
* const err = new Error('kaboom');
* process.nextTick(() => {
* ee.emit('error', err);
* });
*
* try {
* await once(ee, 'myevent');
* } catch (err) {
* console.error('error happened', err);
* }
* ```
*
* The special handling of the `'error'` event is only used when `events.once()`is used to wait for another event. If `events.once()` is used to wait for the
* '`error'` event itself, then it is treated as any other kind of event without
* special handling:
*
* ```js
* import { EventEmitter, once } from 'node:events';
*
* const ee = new EventEmitter();
*
* once(ee, 'error')
* .then(([err]) => console.log('ok', err.message))
* .catch((err) => console.error('error', err.message));
*
* ee.emit('error', new Error('boom'));
*
* // Prints: ok boom
* ```
*
* An `AbortSignal` can be used to cancel waiting for the event:
*
* ```js
* import { EventEmitter, once } from 'node:events';
*
* const ee = new EventEmitter();
* const ac = new AbortController();
*
* async function foo(emitter, event, signal) {
|
* try {
* await once(emitter, event, { signal });
* console.log('event emitted!');
* } catch (error) {
* if (error.name === 'AbortError') {
* console.error('Waiting for the event was canceled!');
* } else {
* console.error('There was an error', error.message);
* }
* }
* }
*
* foo(ee, 'foo', ac.signal);
* ac.abort(); // Abort waiting for the event
* ee.emit('foo'); // Prints: Waiting for the event was canceled!
* ```
* @since v11.13.0, v10.16.0
*/
static once(
emitter: _NodeEventTarget,
eventName: string | symbol,
options?: StaticEventEmitterOptions,
): Promise<any[]>;
static once(emitter: _DOMEventTarget, eventName: string, options?: StaticEventEmitterOptions): Promise<any[]>;
/**
* ```js
* import { on, EventEmitter } from 'node:events';
* import process from 'node:process';
*
* const ee = new EventEmitter();
*
* // Emit later on
* process.nextTick(() => {
* ee.emit('foo', 'bar');
* ee.emit('foo', 42);
* });
*
* for await (const event of on(ee, 'foo')) {
* // The execution of this inner block is synchronous and it
* // processes one event at a time (even with await). Do not use
* // if concurrent execution is required.
* console.log(event); // prints ['bar'] [42]
* }
* // Unreachable here
* ```
*
* Returns an `AsyncIterator` that iterates `eventName` events. It will throw
* if the `EventEmitter` emits `'error'`. It removes all listeners when
* exiting the loop. The `value` returned by each iteration is an array
* composed of the emitted event arguments.
*
* An `AbortSignal` can be used to cancel waiting on events:
*
* ```js
* import { on, EventEmitter } from 'node:events';
* import process from 'node:process';
*
* const ac = new AbortController();
*
* (async () => {
* const ee = new EventEmitter();
*
* // Emit later on
* process.nextTick(() => {
* ee.emit('foo', 'bar');
* ee.emit('foo', 42);
* });
*
* for await (const event of on(ee, 'foo', { signal: ac.signal })) {
* // The execution of this inner block is synchronous and it
* // processes one event at a time (even with await). Do not use
* // if concurrent execution is required.
* console.log(event); // prints ['bar'] [42]
* }
* // Unreachable here
* })();
*
* process.nextTick(() => ac.abort());
* ```
* @since v13.6.0, v12.16.0
* @param eventName The name of the event being listened for
* @return that iterates `eventName` events emitted by the `emitter`
*/
static on(
emitter: NodeJS.EventEmitter,
eventName: string,
options?: StaticEventEmitterOptions,
): AsyncIterableIterator<any>;
/**
* A class method that returns the number of listeners for the given `eventName`registered on the given `emitter`.
*
* ```js
* import { EventEmitter, listenerCount } from 'node:events';
*
* const myEmitter = new EventEmitter();
* myEmitter.on('event', () => {});
* myEmitter.on('event', () => {});
* console.log(listenerCount(myEmitter, 'event'));
* // Prints: 2
* ```
* @since v0.9.12
* @deprecated Since v3.2.0 - Use `listenerCount` instead.
* @param emitter The emitter to query
* @param ev |
entName The event name
*/
static listenerCount(emitter: NodeJS.EventEmitter, eventName: string | symbol): number;
/**
* Returns a copy of the array of listeners for the event named `eventName`.
*
* For `EventEmitter`s this behaves exactly the same as calling `.listeners` on
* the emitter.
*
* For `EventTarget`s this is the only way to get the event listeners for the
* event target. This is useful for debugging and diagnostic purposes.
*
* ```js
* import { getEventListeners, EventEmitter } from 'node:events';
*
* {
* const ee = new EventEmitter();
* const listener = () => console.log('Events are fun');
* ee.on('foo', listener);
* console.log(getEventListeners(ee, 'foo')); // [ [Function: listener] ]
* }
* {
* const et = new EventTarget();
* const listener = () => console.log('Events are fun');
* et.addEventListener('foo', listener);
* console.log(getEventListeners(et, 'foo')); // [ [Function: listener] ]
* }
* ```
* @since v15.2.0, v14.17.0
*/
static getEventListeners(emitter: _DOMEventTarget | NodeJS.EventEmitter, name: string | symbol): Function[];
/**
* Returns the currently set max amount of listeners.
*
* For `EventEmitter`s this behaves exactly the same as calling `.getMaxListeners` on
* the emitter.
*
* For `EventTarget`s this is the only way to get the max event listeners for the
* event target. If the number of event handlers on a single EventTarget exceeds
* the max set, the EventTarget will print a warning.
*
* ```js
* import { getMaxListeners, setMaxListeners, EventEmitter } from 'node:events';
*
* {
* const ee = new EventEmitter();
* console.log(getMaxListeners(ee)); // 10
* setMaxListeners(11, ee);
* console.log(getMaxListeners(ee)); // 11
* }
* {
* const et = new EventTarget();
* console.log(getMaxListeners(et)); // 10
* setMaxListeners(11, et);
* console.log(getMaxListeners(et)); // 11
* }
* ```
* @since v19.9.0
*/
static getMaxListeners(emitter: _DOMEventTarget | NodeJS.EventEmitter): number;
/**
* ```js
* import { setMaxListeners, EventEmitter } from 'node:events';
*
* const target = new EventTarget();
* const emitter = new EventEmitter();
*
* setMaxListeners(5, target, emitter);
* ```
* @since v15.4.0
* @param n A non-negative number. The maximum number of listeners per `EventTarget` event.
* @param eventsTargets Zero or more {EventTarget} or {EventEmitter} instances. If none are specified, `n` is set as the default max for all newly created {EventTarget} and {EventEmitter}
* objects.
*/
static setMaxListeners(n?: number, ...eventTargets: Array<_DOMEventTarget | NodeJS.EventEmitter>): void;
/**
* Listens once to the `abort` event on the provided `signal`.
*
* Listening to the `abort` event on abort signals is unsafe and may
* lead to resource leaks since another third party with the signal can
* call `e.stopImmediatePropagation()`. Unfortunately Node.js cannot change
* this since it would violate the web standard. Additionally, the original
* API makes it easy to forget to remove listeners.
*
* This API allows safely using `AbortSignal`s in Node.js APIs by solving these
* two issues by listening to the event such that `stopImmediatePropagation` does
* not prevent the listener from running.
*
* Returns a dispo |
sable so that it may be unsubscribed from more easily.
*
* ```js
* import { addAbortListener } from 'node:events';
*
* function example(signal) {
* let disposable;
* try {
* signal.addEventListener('abort', (e) => e.stopImmediatePropagation());
* disposable = addAbortListener(signal, (e) => {
* // Do something when signal is aborted.
* });
* } finally {
* disposable?.[Symbol.dispose]();
* }
* }
* ```
* @since v20.5.0
* @experimental
* @return Disposable that removes the `abort` listener.
*/
static addAbortListener(signal: AbortSignal, resource: (event: Event) => void): Disposable;
/**
* This symbol shall be used to install a listener for only monitoring `'error'`events. Listeners installed using this symbol are called before the regular`'error'` listeners are called.
*
* Installing a listener using this symbol does not change the behavior once an`'error'` event is emitted. Therefore, the process will still crash if no
* regular `'error'` listener is installed.
* @since v13.6.0, v12.17.0
*/
static readonly errorMonitor: unique symbol;
/**
* Value: `Symbol.for('nodejs.rejection')`
*
* See how to write a custom `rejection handler`.
* @since v13.4.0, v12.16.0
*/
static readonly captureRejectionSymbol: unique symbol;
/**
* Value: [boolean](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Boolean_type)
*
* Change the default `captureRejections` option on all new `EventEmitter` objects.
* @since v13.4.0, v12.16.0
*/
static captureRejections: boolean;
/**
* By default, a maximum of `10` listeners can be registered for any single
* event. This limit can be changed for individual `EventEmitter` instances
* using the `emitter.setMaxListeners(n)` method. To change the default
* for _all_`EventEmitter` instances, the `events.defaultMaxListeners`property can be used. If this value is not a positive number, a `RangeError`is thrown.
*
* Take caution when setting the `events.defaultMaxListeners` because the
* change affects _all_`EventEmitter` instances, including those created before
* the change is made. However, calling `emitter.setMaxListeners(n)` still has
* precedence over `events.defaultMaxListeners`.
*
* This is not a hard limit. The `EventEmitter` instance will allow
* more listeners to be added but will output a trace warning to stderr indicating
* that a "possible EventEmitter memory leak" has been detected. For any single`EventEmitter`, the `emitter.getMaxListeners()` and `emitter.setMaxListeners()`methods can be used to
* temporarily avoid this warning:
*
* ```js
* import { EventEmitter } from 'node:events';
* const emitter = new EventEmitter();
* emitter.setMaxListeners(emitter.getMaxListeners() + 1);
* emitter.once('event', () => {
* // do stuff
* emitter.setMaxListeners(Math.max(emitter.getMaxListeners() - 1, 0));
* });
* ```
*
* The `--trace-warnings` command-line flag can be used to display the
* stack trace for such warnings.
*
* The emitted warning can be inspected with `process.on('warning')` and will
* have the additional `emitter`, `type`, and `count` properties, referring to
* the event emitter instance, the event's name and the number of attached
* listeners, respectively.
* Its `name` property is set to `'MaxListenersExceededWarning'`.
* @since v0.11.2
*/
static de |
faultMaxListeners: number;
}
import internal = require("node:events");
namespace EventEmitter {
// Should just be `export { EventEmitter }`, but that doesn't work in TypeScript 3.4
export { internal as EventEmitter };
export interface Abortable {
/**
* When provided the corresponding `AbortController` can be used to cancel an asynchronous action.
*/
signal?: AbortSignal | undefined;
}
export interface EventEmitterReferencingAsyncResource extends AsyncResource {
readonly eventEmitter: EventEmitterAsyncResource;
}
export interface EventEmitterAsyncResourceOptions extends AsyncResourceOptions, EventEmitterOptions {
/**
* The type of async event, this is required when instantiating `EventEmitterAsyncResource`
* directly rather than as a child class.
* @default new.target.name if instantiated as a child class.
*/
name?: string;
}
/**
* Integrates `EventEmitter` with `AsyncResource` for `EventEmitter`s that
* require manual async tracking. Specifically, all events emitted by instances
* of `events.EventEmitterAsyncResource` will run within its `async context`.
*
* ```js
* import { EventEmitterAsyncResource, EventEmitter } from 'node:events';
* import { notStrictEqual, strictEqual } from 'node:assert';
* import { executionAsyncId, triggerAsyncId } from 'node:async_hooks';
*
* // Async tracking tooling will identify this as 'Q'.
* const ee1 = new EventEmitterAsyncResource({ name: 'Q' });
*
* // 'foo' listeners will run in the EventEmitters async context.
* ee1.on('foo', () => {
* strictEqual(executionAsyncId(), ee1.asyncId);
* strictEqual(triggerAsyncId(), ee1.triggerAsyncId);
* });
*
* const ee2 = new EventEmitter();
*
* // 'foo' listeners on ordinary EventEmitters that do not track async
* // context, however, run in the same async context as the emit().
* ee2.on('foo', () => {
* notStrictEqual(executionAsyncId(), ee2.asyncId);
* notStrictEqual(triggerAsyncId(), ee2.triggerAsyncId);
* });
*
* Promise.resolve().then(() => {
* ee1.emit('foo');
* ee2.emit('foo');
* });
* ```
*
* The `EventEmitterAsyncResource` class has the same methods and takes the
* same options as `EventEmitter` and `AsyncResource` themselves.
* @since v17.4.0, v16.14.0
*/
export class EventEmitterAsyncResource extends EventEmitter {
/**
* @param options Only optional in child class.
*/
constructor(options?: EventEmitterAsyncResourceOptions);
/**
* Call all `destroy` hooks. This should only ever be called once. An error will
* be thrown if it is called more than once. This **must** be manually called. If
* the resource is left to be collected by the GC then the `destroy` hooks will
* never be called.
*/
emitDestroy(): void;
/**
* The unique `asyncId` assigned to the resource.
*/
readonly asyncId: number;
/**
* The same triggerAsyncId that is passed to the AsyncResource constructor.
*/
readonly triggerAsyncId: number;
/**
* The returned `AsyncResource` object has an additional `eventEmitter` property
* that provides a reference to this `EventEmitterAsyncResource`.
*/
readonly asyncResource: EventEmitterReferencingAsyncResource;
}
}
global {
namespace NodeJS {
interfac |
e EventEmitter {
[EventEmitter.captureRejectionSymbol]?(error: Error, event: string, ...args: any[]): void;
/**
* Alias for `emitter.on(eventName, listener)`.
* @since v0.1.26
*/
addListener(eventName: string | symbol, listener: (...args: any[]) => void): this;
/**
* Adds the `listener` function to the end of the listeners array for the
* event named `eventName`. No checks are made to see if the `listener` has
* already been added. Multiple calls passing the same combination of `eventName`and `listener` will result in the `listener` being added, and called, multiple
* times.
*
* ```js
* server.on('connection', (stream) => {
* console.log('someone connected!');
* });
* ```
*
* Returns a reference to the `EventEmitter`, so that calls can be chained.
*
* By default, event listeners are invoked in the order they are added. The`emitter.prependListener()` method can be used as an alternative to add the
* event listener to the beginning of the listeners array.
*
* ```js
* import { EventEmitter } from 'node:events';
* const myEE = new EventEmitter();
* myEE.on('foo', () => console.log('a'));
* myEE.prependListener('foo', () => console.log('b'));
* myEE.emit('foo');
* // Prints:
* // b
* // a
* ```
* @since v0.1.101
* @param eventName The name of the event.
* @param listener The callback function
*/
on(eventName: string | symbol, listener: (...args: any[]) => void): this;
/**
* Adds a **one-time**`listener` function for the event named `eventName`. The
* next time `eventName` is triggered, this listener is removed and then invoked.
*
* ```js
* server.once('connection', (stream) => {
* console.log('Ah, we have our first user!');
* });
* ```
*
* Returns a reference to the `EventEmitter`, so that calls can be chained.
*
* By default, event listeners are invoked in the order they are added. The`emitter.prependOnceListener()` method can be used as an alternative to add the
* event listener to the beginning of the listeners array.
*
* ```js
* import { EventEmitter } from 'node:events';
* const myEE = new EventEmitter();
* myEE.once('foo', () => console.log('a'));
* myEE.prependOnceListener('foo', () => console.log('b'));
* myEE.emit('foo');
* // Prints:
* // b
* // a
* ```
* @since v0.3.0
* @param eventName The name of the event.
* @param listener The callback function
*/
once(eventName: string | symbol, listener: (...args: any[]) => void): this;
/**
* Removes the specified `listener` from the listener array for the event named`eventName`.
*
* ```js
* const callback = (stream) => {
* console.log('someone connected!');
* };
* server.on('connection', callback);
* // ...
* server.removeListener('connection', callback);
* |
```
*
* `removeListener()` will remove, at most, one instance of a listener from the
* listener array. If any single listener has been added multiple times to the
* listener array for the specified `eventName`, then `removeListener()` must be
* called multiple times to remove each instance.
*
* Once an event is emitted, all listeners attached to it at the
* time of emitting are called in order. This implies that any`removeListener()` or `removeAllListeners()` calls _after_ emitting and _before_ the last listener finishes execution
* will not remove them from`emit()` in progress. Subsequent events behave as expected.
*
* ```js
* import { EventEmitter } from 'node:events';
* class MyEmitter extends EventEmitter {}
* const myEmitter = new MyEmitter();
*
* const callbackA = () => {
* console.log('A');
* myEmitter.removeListener('event', callbackB);
* };
*
* const callbackB = () => {
* console.log('B');
* };
*
* myEmitter.on('event', callbackA);
*
* myEmitter.on('event', callbackB);
*
* // callbackA removes listener callbackB but it will still be called.
* // Internal listener array at time of emit [callbackA, callbackB]
* myEmitter.emit('event');
* // Prints:
* // A
* // B
*
* // callbackB is now removed.
* // Internal listener array [callbackA]
* myEmitter.emit('event');
* // Prints:
* // A
* ```
*
* Because listeners are managed using an internal array, calling this will
* change the position indices of any listener registered _after_ the listener
* being removed. This will not impact the order in which listeners are called,
* but it means that any copies of the listener array as returned by
* the `emitter.listeners()` method will need to be recreated.
*
* When a single function has been added as a handler multiple times for a single
* event (as in the example below), `removeListener()` will remove the most
* recently added instance. In the example the `once('ping')`listener is removed:
*
* ```js
* import { EventEmitter } from 'node:events';
* const ee = new EventEmitter();
*
* function pong() {
* console.log('pong');
* }
*
* ee.on('ping', pong);
* ee.once('ping', pong);
* ee.removeListener('ping', pong);
*
* ee.emit('ping');
* ee.emit('ping');
* ```
*
* Returns a reference to the `EventEmitter`, so that calls can be chained.
* @since v0.1.26
*/
removeListener(eventName: string | symbol, listener: (...args: any[]) => void): this;
/**
* Alias for `emitter.removeListener()`.
* @since v10.0.0
*/
off(eventName: string | symbol, listener: (...args: any[]) => void): this;
/**
* Removes all listeners, or those of the specified `eventName`.
*
* It is bad practice to remove lis |
teners added elsewhere in the code,
* particularly when the `EventEmitter` instance was created by some other
* component or module (e.g. sockets or file streams).
*
* Returns a reference to the `EventEmitter`, so that calls can be chained.
* @since v0.1.26
*/
removeAllListeners(event?: string | symbol): this;
/**
* By default `EventEmitter`s will print a warning if more than `10` listeners are
* added for a particular event. This is a useful default that helps finding
* memory leaks. The `emitter.setMaxListeners()` method allows the limit to be
* modified for this specific `EventEmitter` instance. The value can be set to`Infinity` (or `0`) to indicate an unlimited number of listeners.
*
* Returns a reference to the `EventEmitter`, so that calls can be chained.
* @since v0.3.5
*/
setMaxListeners(n: number): this;
/**
* Returns the current max listener value for the `EventEmitter` which is either
* set by `emitter.setMaxListeners(n)` or defaults to {@link defaultMaxListeners}.
* @since v1.0.0
*/
getMaxListeners(): number;
/**
* Returns a copy of the array of listeners for the event named `eventName`.
*
* ```js
* server.on('connection', (stream) => {
* console.log('someone connected!');
* });
* console.log(util.inspect(server.listeners('connection')));
* // Prints: [ [Function] ]
* ```
* @since v0.1.26
*/
listeners(eventName: string | symbol): Function[];
/**
* Returns a copy of the array of listeners for the event named `eventName`,
* including any wrappers (such as those created by `.once()`).
*
* ```js
* import { EventEmitter } from 'node:events';
* const emitter = new EventEmitter();
* emitter.once('log', () => console.log('log once'));
*
* // Returns a new Array with a function `onceWrapper` which has a property
* // `listener` which contains the original listener bound above
* const listeners = emitter.rawListeners('log');
* const logFnWrapper = listeners[0];
*
* // Logs "log once" to the console and does not unbind the `once` event
* logFnWrapper.listener();
*
* // Logs "log once" to the console and removes the listener
* logFnWrapper();
*
* emitter.on('log', () => console.log('log persistently'));
* // Will return a new Array with a single function bound by `.on()` above
* const newListeners = emitter.rawListeners('log');
*
* // Logs "log persistently" twice
* newListeners[0]();
* emitter.emit('log');
* ```
* @since v9.4.0
*/
rawListeners(eventName: string | symbol): Function[];
/**
* Synchronously calls each of the listeners registered for the event named`eventName`, in the order they were registered, passing the supplied arguments
* to each.
*
* Returns `true` if the event had listeners, `false` otherwise.
*
* ```js
* import { EventEmitter } from 'node:events';
|
* const myEmitter = new EventEmitter();
*
* // First listener
* myEmitter.on('event', function firstListener() {
* console.log('Helloooo! first listener');
* });
* // Second listener
* myEmitter.on('event', function secondListener(arg1, arg2) {
* console.log(`event with parameters ${arg1}, ${arg2} in second listener`);
* });
* // Third listener
* myEmitter.on('event', function thirdListener(...args) {
* const parameters = args.join(', ');
* console.log(`event with parameters ${parameters} in third listener`);
* });
*
* console.log(myEmitter.listeners('event'));
*
* myEmitter.emit('event', 1, 2, 3, 4, 5);
*
* // Prints:
* // [
* // [Function: firstListener],
* // [Function: secondListener],
* // [Function: thirdListener]
* // ]
* // Helloooo! first listener
* // event with parameters 1, 2 in second listener
* // event with parameters 1, 2, 3, 4, 5 in third listener
* ```
* @since v0.1.26
*/
emit(eventName: string | symbol, ...args: any[]): boolean;
/**
* Returns the number of listeners listening for the event named `eventName`.
* If `listener` is provided, it will return how many times the listener is found
* in the list of the listeners of the event.
* @since v3.2.0
* @param eventName The name of the event being listened for
* @param listener The event handler function
*/
listenerCount(eventName: string | symbol, listener?: Function): number;
/**
* Adds the `listener` function to the _beginning_ of the listeners array for the
* event named `eventName`. No checks are made to see if the `listener` has
* already been added. Multiple calls passing the same combination of `eventName`and `listener` will result in the `listener` being added, and called, multiple
* times.
*
* ```js
* server.prependListener('connection', (stream) => {
* console.log('someone connected!');
* });
* ```
*
* Returns a reference to the `EventEmitter`, so that calls can be chained.
* @since v6.0.0
* @param eventName The name of the event.
* @param listener The callback function
*/
prependListener(eventName: string | symbol, listener: (...args: any[]) => void): this;
/**
* Adds a **one-time**`listener` function for the event named `eventName` to the _beginning_ of the listeners array. The next time `eventName` is triggered, this
* listener is removed, and then invoked.
*
* ```js
* server.prependOnceListener('connection', (stream) => {
* console.log('Ah, we have our first user!');
* });
* ```
*
* Returns a reference to the `EventEmitter`, so that calls can be chained.
* @since v6.0.0
* @param eventName The name of the event.
* @param listener The callback function
*/
prependOnceListener(eventName: string | symbol, listener: (...args: any[]) => void): this;
/**
* Ret |
urns an array listing the events for which the emitter has registered
* listeners. The values in the array are strings or `Symbol`s.
*
* ```js
* import { EventEmitter } from 'node:events';
*
* const myEE = new EventEmitter();
* myEE.on('foo', () => {});
* myEE.on('bar', () => {});
*
* const sym = Symbol('symbol');
* myEE.on(sym, () => {});
*
* console.log(myEE.eventNames());
* // Prints: [ 'foo', 'bar', Symbol(symbol) ]
* ```
* @since v6.0.0
*/
eventNames(): Array<string | symbol>;
}
}
}
export = EventEmitter;
}
declare module "node:events" {
import events = require("events");
export = events;
}
|
/**
* The `node:os` module provides operating system-related utility methods and
* properties. It can be accessed using:
*
* ```js
* const os = require('node:os');
* ```
* @see [source](https://github.com/nodejs/node/blob/v20.2.0/lib/os.js)
*/
declare module "os" {
interface CpuInfo {
model: string;
speed: number;
times: {
user: number;
nice: number;
sys: number;
idle: number;
irq: number;
};
}
interface NetworkInterfaceBase {
address: string;
netmask: string;
mac: string;
internal: boolean;
cidr: string | null;
}
interface NetworkInterfaceInfoIPv4 extends NetworkInterfaceBase {
family: "IPv4";
scopeid?: undefined;
}
interface NetworkInterfaceInfoIPv6 extends NetworkInterfaceBase {
family: "IPv6";
scopeid: number;
}
interface UserInfo<T> {
username: T;
uid: number;
gid: number;
shell: T | null;
homedir: T;
}
type NetworkInterfaceInfo = NetworkInterfaceInfoIPv4 | NetworkInterfaceInfoIPv6;
/**
* Returns the host name of the operating system as a string.
* @since v0.3.3
*/
function hostname(): string;
/**
* Returns an array containing the 1, 5, and 15 minute load averages.
*
* The load average is a measure of system activity calculated by the operating
* system and expressed as a fractional number.
*
* The load average is a Unix-specific concept. On Windows, the return value is
* always `[0, 0, 0]`.
* @since v0.3.3
*/
function loadavg(): number[];
/**
* Returns the system uptime in number of seconds.
* @since v0.3.3
*/
function uptime(): number;
/**
* Returns the amount of free system memory in bytes as an integer.
* @since v0.3.3
*/
function freemem(): number;
/**
* Returns the total amount of system memory in bytes as an integer.
* @since v0.3.3
*/
function totalmem(): number;
/**
* Returns an array of objects containing information about each logical CPU core.
* The array will be empty if no CPU information is available, such as if the`/proc` file system is unavailable.
*
* The properties included on each object include:
*
* ```js
* [
* {
* model: 'Intel(R) Core(TM) i7 CPU 860 @ 2.80GHz',
* speed: 2926,
* times: {
* user: 252020,
* nice: 0,
* sys: 30340,
* idle: 1070356870,
* irq: 0,
* },
* },
* {
* model: 'Intel(R) Core(TM) i7 CPU 860 @ 2.80GHz',
* speed: 2926,
* times: {
* user: 306960,
* nice: 0,
* sys: 26980,
* idle: 1071569080,
* irq: 0,
* },
* },
* {
* model: 'Intel(R) Core(TM) i7 CPU 860 @ 2.80GHz',
* speed: 2926,
* times: {
* user: 248450,
* nice: 0,
* sys: 21750,
* idle: 1070919370,
* irq: 0,
* },
* },
* {
* model: 'Intel(R) Core(TM) i7 CPU 860 @ 2.80GHz',
* speed: 2926,
* times: {
* user: 256880,
* nice: 0,
* sys: 19430,
* idle: 1070905480,
* irq: 20,
* },
* },
* ]
* ```
*
* `nice` values are POSIX-only. On Windows, the `nice` values of all processors
* are always 0.
*
* `os.cpus().length` should not be used to calculate the amount of parallelism
* available to an application. Use {@link availableParallelism} for this purpose.
* @since v0.3.3
*/
function cpus(): CpuInfo[];
/**
* Returns an estimate of the default amount of parallelism a program should use.
* Always return |
s a value greater than zero.
*
* This function is a small wrapper about libuv's [`uv_available_parallelism()`](https://docs.libuv.org/en/v1.x/misc.html#c.uv_available_parallelism).
* @since v19.4.0, v18.14.0
*/
function availableParallelism(): number;
/**
* Returns the operating system name as returned by [`uname(3)`](https://linux.die.net/man/3/uname). For example, it
* returns `'Linux'` on Linux, `'Darwin'` on macOS, and `'Windows_NT'` on Windows.
*
* See [https://en.wikipedia.org/wiki/Uname#Examples](https://en.wikipedia.org/wiki/Uname#Examples) for additional information
* about the output of running [`uname(3)`](https://linux.die.net/man/3/uname) on various operating systems.
* @since v0.3.3
*/
function type(): string;
/**
* Returns the operating system as a string.
*
* On POSIX systems, the operating system release is determined by calling [`uname(3)`](https://linux.die.net/man/3/uname). On Windows, `GetVersionExW()` is used. See
* [https://en.wikipedia.org/wiki/Uname#Examples](https://en.wikipedia.org/wiki/Uname#Examples) for more information.
* @since v0.3.3
*/
function release(): string;
/**
* Returns an object containing network interfaces that have been assigned a
* network address.
*
* Each key on the returned object identifies a network interface. The associated
* value is an array of objects that each describe an assigned network address.
*
* The properties available on the assigned network address object include:
*
* ```js
* {
* lo: [
* {
* address: '127.0.0.1',
* netmask: '255.0.0.0',
* family: 'IPv4',
* mac: '00:00:00:00:00:00',
* internal: true,
* cidr: '127.0.0.1/8'
* },
* {
* address: '::1',
* netmask: 'ffff:ffff:ffff:ffff:ffff:ffff:ffff:ffff',
* family: 'IPv6',
* mac: '00:00:00:00:00:00',
* scopeid: 0,
* internal: true,
* cidr: '::1/128'
* }
* ],
* eth0: [
* {
* address: '192.168.1.108',
* netmask: '255.255.255.0',
* family: 'IPv4',
* mac: '01:02:03:0a:0b:0c',
* internal: false,
* cidr: '192.168.1.108/24'
* },
* {
* address: 'fe80::a00:27ff:fe4e:66a1',
* netmask: 'ffff:ffff:ffff:ffff::',
* family: 'IPv6',
* mac: '01:02:03:0a:0b:0c',
* scopeid: 1,
* internal: false,
* cidr: 'fe80::a00:27ff:fe4e:66a1/64'
* }
* ]
* }
* ```
* @since v0.6.0
*/
function networkInterfaces(): NodeJS.Dict<NetworkInterfaceInfo[]>;
/**
* Returns the string path of the current user's home directory.
*
* On POSIX, it uses the `$HOME` environment variable if defined. Otherwise it
* uses the [effective UID](https://en.wikipedia.org/wiki/User_identifier#Effective_user_ID) to look up the user's home directory.
*
* On Windows, it uses the `USERPROFILE` environment variable if defined.
* Otherwise it uses the path to the profile directory of the current user.
* @since v2.3.0
*/
function homedir(): string;
/**
* Returns information about the currently effective user. On POSIX platforms,
* this is typically a subset of the password file. The returned object includes
* the `username`, `uid`, `gid`, `shell`, and `homedir`. On Windows, the `uid` and`gid` fields are `-1`, and `shell` is `null`.
*
* The value of `homedir` returned by `os.userInfo()` is provided by the operating
* system. This differs from the result of `os.homedir()`, which queries
* environment variables for the home directory before falling back to the
* operating system response.
*
* Throws a `SystemError` if a user |
has no `username` or `homedir`.
* @since v6.0.0
*/
function userInfo(options: { encoding: "buffer" }): UserInfo<Buffer>;
function userInfo(options?: { encoding: BufferEncoding }): UserInfo<string>;
type SignalConstants = {
[key in NodeJS.Signals]: number;
};
namespace constants {
const UV_UDP_REUSEADDR: number;
namespace signals {}
const signals: SignalConstants;
namespace errno {
const E2BIG: number;
const EACCES: number;
const EADDRINUSE: number;
const EADDRNOTAVAIL: number;
const EAFNOSUPPORT: number;
const EAGAIN: number;
const EALREADY: number;
const EBADF: number;
const EBADMSG: number;
const EBUSY: number;
const ECANCELED: number;
const ECHILD: number;
const ECONNABORTED: number;
const ECONNREFUSED: number;
const ECONNRESET: number;
const EDEADLK: number;
const EDESTADDRREQ: number;
const EDOM: number;
const EDQUOT: number;
const EEXIST: number;
const EFAULT: number;
const EFBIG: number;
const EHOSTUNREACH: number;
const EIDRM: number;
const EILSEQ: number;
const EINPROGRESS: number;
const EINTR: number;
const EINVAL: number;
const EIO: number;
const EISCONN: number;
const EISDIR: number;
const ELOOP: number;
const EMFILE: number;
const EMLINK: number;
const EMSGSIZE: number;
const EMULTIHOP: number;
const ENAMETOOLONG: number;
const ENETDOWN: number;
const ENETRESET: number;
const ENETUNREACH: number;
const ENFILE: number;
const ENOBUFS: number;
const ENODATA: number;
const ENODEV: number;
const ENOENT: number;
const ENOEXEC: number;
const ENOLCK: number;
const ENOLINK: number;
const ENOMEM: number;
const ENOMSG: number;
const ENOPROTOOPT: number;
const ENOSPC: number;
const ENOSR: number;
const ENOSTR: number;
const ENOSYS: number;
const ENOTCONN: number;
const ENOTDIR: number;
const ENOTEMPTY: number;
const ENOTSOCK: number;
const ENOTSUP: number;
const ENOTTY: number;
const ENXIO: number;
const EOPNOTSUPP: number;
const EOVERFLOW: number;
const EPERM: number;
const EPIPE: number;
const EPROTO: number;
const EPROTONOSUPPORT: number;
const EPROTOTYPE: number;
const ERANGE: number;
const EROFS: number;
const ESPIPE: number;
const ESRCH: number;
const ESTALE: number;
const ETIME: number;
const ETIMEDOUT: number;
const ETXTBSY: number;
const EWOULDBLOCK: number;
const EXDEV: number;
const WSAEINTR: number;
const WSAEBADF: number;
const WSAEACCES: number;
const WSAEFAULT: number;
const WSAEINVAL: number;
const WSAEMFILE: number;
const WSAEWOULDBLOCK: number;
const WSAEINPROGRESS: number;
const WSAEALREADY: number;
const WSAENOTSOCK: number;
const WSAEDESTADDRREQ: number;
const WSAEMSGSIZE: number;
const WSAEPROTOTYPE: number;
const WSAENOPROTOOPT: number;
const WSAEPROTONOSUPPORT: number;
const WSAESOCKTNOSUPPORT: number;
const WSAEOPNOTSUPP: number;
const WSAEPFNOSUPPORT: number;
const WSAEAFNOSUPP |
ORT: number;
const WSAEADDRINUSE: number;
const WSAEADDRNOTAVAIL: number;
const WSAENETDOWN: number;
const WSAENETUNREACH: number;
const WSAENETRESET: number;
const WSAECONNABORTED: number;
const WSAECONNRESET: number;
const WSAENOBUFS: number;
const WSAEISCONN: number;
const WSAENOTCONN: number;
const WSAESHUTDOWN: number;
const WSAETOOMANYREFS: number;
const WSAETIMEDOUT: number;
const WSAECONNREFUSED: number;
const WSAELOOP: number;
const WSAENAMETOOLONG: number;
const WSAEHOSTDOWN: number;
const WSAEHOSTUNREACH: number;
const WSAENOTEMPTY: number;
const WSAEPROCLIM: number;
const WSAEUSERS: number;
const WSAEDQUOT: number;
const WSAESTALE: number;
const WSAEREMOTE: number;
const WSASYSNOTREADY: number;
const WSAVERNOTSUPPORTED: number;
const WSANOTINITIALISED: number;
const WSAEDISCON: number;
const WSAENOMORE: number;
const WSAECANCELLED: number;
const WSAEINVALIDPROCTABLE: number;
const WSAEINVALIDPROVIDER: number;
const WSAEPROVIDERFAILEDINIT: number;
const WSASYSCALLFAILURE: number;
const WSASERVICE_NOT_FOUND: number;
const WSATYPE_NOT_FOUND: number;
const WSA_E_NO_MORE: number;
const WSA_E_CANCELLED: number;
const WSAEREFUSED: number;
}
namespace priority {
const PRIORITY_LOW: number;
const PRIORITY_BELOW_NORMAL: number;
const PRIORITY_NORMAL: number;
const PRIORITY_ABOVE_NORMAL: number;
const PRIORITY_HIGH: number;
const PRIORITY_HIGHEST: number;
}
}
const devNull: string;
const EOL: string;
/**
* Returns the operating system CPU architecture for which the Node.js binary was
* compiled. Possible values are `'arm'`, `'arm64'`, `'ia32'`, `'loong64'`,`'mips'`, `'mipsel'`, `'ppc'`, `'ppc64'`, `'riscv64'`, `'s390'`, `'s390x'`,
* and `'x64'`.
*
* The return value is equivalent to `process.arch`.
* @since v0.5.0
*/
function arch(): string;
/**
* Returns a string identifying the kernel version.
*
* On POSIX systems, the operating system release is determined by calling [`uname(3)`](https://linux.die.net/man/3/uname). On Windows, `RtlGetVersion()` is used, and if it is not
* available, `GetVersionExW()` will be used. See [https://en.wikipedia.org/wiki/Uname#Examples](https://en.wikipedia.org/wiki/Uname#Examples) for more information.
* @since v13.11.0, v12.17.0
*/
function version(): string;
/**
* Returns a string identifying the operating system platform for which
* the Node.js binary was compiled. The value is set at compile time.
* Possible values are `'aix'`, `'darwin'`, `'freebsd'`,`'linux'`,`'openbsd'`, `'sunos'`, and `'win32'`.
*
* The return value is equivalent to `process.platform`.
*
* The value `'android'` may also be returned if Node.js is built on the Android
* operating system. [Android support is experimental](https://github.com/nodejs/node/blob/HEAD/BUILDING.md#androidandroid-based-devices-eg-firefox-os).
* @since v0.5.0
*/
function platform(): NodeJS.Platform;
/**
* Returns the machine type as a string, such as `arm`, `arm64`, `aarch64`,`mips`, `mips64`, `ppc64`, `ppc64le`, `s390`, `s390x`, `i386`, `i686`, `x86_64`.
*
* On POSIX systems, the machine type is determined by calling [`uname(3)`](https://linux.die.net/man/3/uname). On Windows, `RtlGetVersion()` is used, and if it is not
* available, `GetVersionExW()` will be used. See [https://en.wikipedia.org/wiki/Uname#Examples](https:// |
en.wikipedia.org/wiki/Uname#Examples) for more information.
* @since v18.9.0, v16.18.0
*/
function machine(): string;
/**
* Returns the operating system's default directory for temporary files as a
* string.
* @since v0.9.9
*/
function tmpdir(): string;
/**
* Returns a string identifying the endianness of the CPU for which the Node.js
* binary was compiled.
*
* Possible values are `'BE'` for big endian and `'LE'` for little endian.
* @since v0.9.4
*/
function endianness(): "BE" | "LE";
/**
* Returns the scheduling priority for the process specified by `pid`. If `pid` is
* not provided or is `0`, the priority of the current process is returned.
* @since v10.10.0
* @param [pid=0] The process ID to retrieve scheduling priority for.
*/
function getPriority(pid?: number): number;
/**
* Attempts to set the scheduling priority for the process specified by `pid`. If`pid` is not provided or is `0`, the process ID of the current process is used.
*
* The `priority` input must be an integer between `-20` (high priority) and `19`(low priority). Due to differences between Unix priority levels and Windows
* priority classes, `priority` is mapped to one of six priority constants in`os.constants.priority`. When retrieving a process priority level, this range
* mapping may cause the return value to be slightly different on Windows. To avoid
* confusion, set `priority` to one of the priority constants.
*
* On Windows, setting priority to `PRIORITY_HIGHEST` requires elevated user
* privileges. Otherwise the set priority will be silently reduced to`PRIORITY_HIGH`.
* @since v10.10.0
* @param [pid=0] The process ID to set scheduling priority for.
* @param priority The scheduling priority to assign to the process.
*/
function setPriority(priority: number): void;
function setPriority(pid: number, priority: number): void;
}
declare module "node:os" {
export * from "os";
}
|
/**
* `Buffer` objects are used to represent a fixed-length sequence of bytes. Many
* Node.js APIs support `Buffer`s.
*
* The `Buffer` class is a subclass of JavaScript's [`Uint8Array`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Uint8Array) class and
* extends it with methods that cover additional use cases. Node.js APIs accept
* plain [`Uint8Array`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Uint8Array) s wherever `Buffer`s are supported as well.
*
* While the `Buffer` class is available within the global scope, it is still
* recommended to explicitly reference it via an import or require statement.
*
* ```js
* import { Buffer } from 'node:buffer';
*
* // Creates a zero-filled Buffer of length 10.
* const buf1 = Buffer.alloc(10);
*
* // Creates a Buffer of length 10,
* // filled with bytes which all have the value `1`.
* const buf2 = Buffer.alloc(10, 1);
*
* // Creates an uninitialized buffer of length 10.
* // This is faster than calling Buffer.alloc() but the returned
* // Buffer instance might contain old data that needs to be
* // overwritten using fill(), write(), or other functions that fill the Buffer's
* // contents.
* const buf3 = Buffer.allocUnsafe(10);
*
* // Creates a Buffer containing the bytes [1, 2, 3].
* const buf4 = Buffer.from([1, 2, 3]);
*
* // Creates a Buffer containing the bytes [1, 1, 1, 1] – the entries
* // are all truncated using `(value & 255)` to fit into the range 0–255.
* const buf5 = Buffer.from([257, 257.5, -255, '1']);
*
* // Creates a Buffer containing the UTF-8-encoded bytes for the string 'tést':
* // [0x74, 0xc3, 0xa9, 0x73, 0x74] (in hexadecimal notation)
* // [116, 195, 169, 115, 116] (in decimal notation)
* const buf6 = Buffer.from('tést');
*
* // Creates a Buffer containing the Latin-1 bytes [0x74, 0xe9, 0x73, 0x74].
* const buf7 = Buffer.from('tést', 'latin1');
* ```
* @see [source](https://github.com/nodejs/node/blob/v20.2.0/lib/buffer.js)
*/
declare module "buffer" {
import { BinaryLike } from "node:crypto";
import { ReadableStream as WebReadableStream } from "node:stream/web";
/**
* 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.
* @since v19.4.0, v18.14.0
* @param input The input to validate.
*/
export function isUtf8(input: Buffer | ArrayBuffer | NodeJS.TypedArray): 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.
* @since v19.6.0, v18.15.0
* @param input The input to validate.
*/
export function isAscii(input: Buffer | ArrayBuffer | NodeJS.TypedArray): boolean;
export const INSPECT_MAX_BYTES: number;
export const kMaxLength: number;
export const kStringMaxLength: number;
export const constants: {
MAX_LENGTH: number;
MAX_STRING_LENGTH: number;
};
export type TranscodeEncoding =
| "ascii"
| "utf8"
| "utf-8"
| "utf16le"
| "utf-16le"
| "ucs2"
| "ucs-2"
| "latin1"
| "binary";
/**
* 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 transcoding process will use substitution characters if a given byte
* sequence cannot be adequately represented in the target encoding. For instance:
*
|
* ```js
* import { Buffer, transcode } from '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`.
* @since v7.1.0
* @param source A `Buffer` or `Uint8Array` instance.
* @param fromEnc The current encoding.
* @param toEnc To target encoding.
*/
export function transcode(source: Uint8Array, fromEnc: TranscodeEncoding, toEnc: TranscodeEncoding): Buffer;
export const SlowBuffer: {
/** @deprecated since v6.0.0, use `Buffer.allocUnsafeSlow()` */
new(size: number): Buffer;
prototype: Buffer;
};
/**
* Resolves a `'blob:nodedata:...'` an associated `Blob` object registered using
* a prior call to `URL.createObjectURL()`.
* @since v16.7.0
* @experimental
* @param id A `'blob:nodedata:...` URL string returned by a prior call to `URL.createObjectURL()`.
*/
export function resolveObjectURL(id: string): Blob | undefined;
export { Buffer };
/**
* @experimental
*/
export interface BlobOptions {
/**
* @default 'utf8'
*/
encoding?: BufferEncoding | undefined;
/**
* The Blob content-type. The intent is for `type` to convey
* the MIME media type of the data, however no validation of the type format
* is performed.
*/
type?: string | undefined;
}
/**
* A [`Blob`](https://developer.mozilla.org/en-US/docs/Web/API/Blob) encapsulates immutable, raw data that can be safely shared across
* multiple worker threads.
* @since v15.7.0, v14.18.0
*/
export class Blob {
/**
* The total size of the `Blob` in bytes.
* @since v15.7.0, v14.18.0
*/
readonly size: number;
/**
* The content-type of the `Blob`.
* @since v15.7.0, v14.18.0
*/
readonly type: string;
/**
* Creates a new `Blob` object containing a concatenation of the given sources.
*
* {ArrayBuffer}, {TypedArray}, {DataView}, and {Buffer} sources are copied into
* the 'Blob' and can therefore be safely modified after the 'Blob' is created.
*
* String sources are also copied into the `Blob`.
*/
constructor(sources: Array<BinaryLike | Blob>, options?: BlobOptions);
/**
* Returns a promise that fulfills with an [ArrayBuffer](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/ArrayBuffer) containing a copy of
* the `Blob` data.
* @since v15.7.0, v14.18.0
*/
arrayBuffer(): Promise<ArrayBuffer>;
/**
* Creates and returns a new `Blob` containing a subset of this `Blob` objects
* data. The original `Blob` is not altered.
* @since v15.7.0, v14.18.0
* @param start The starting index.
* @param end The ending index.
* @param type The content-type for the new `Blob`
*/
slice(start?: number, end?: number, type?: string): Blob;
/**
* Returns a promise that fulfills with the contents of the `Blob` decoded as a
* UTF-8 string.
* @since v15.7.0, v14.18.0
*/
text(): Promise<string>;
/**
* Returns a new `ReadableStream` that allows the content of the `Blob` to be read.
* @since v16.7.0
*/
stream(): WebReadableStream;
}
export interface FileOptions {
/**
* 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`.
*/
endings?: "nativ |
e" | "transparent";
/** The File content-type. */
type?: string;
/** The last modified date of the file. `Default`: Date.now(). */
lastModified?: number;
}
/**
* A [`File`](https://developer.mozilla.org/en-US/docs/Web/API/File) provides information about files.
* @since v19.2.0, v18.13.0
*/
export class File extends Blob {
constructor(sources: Array<BinaryLike | Blob>, fileName: string, options?: FileOptions);
/**
* The name of the `File`.
* @since v19.2.0, v18.13.0
*/
readonly name: string;
/**
* The last modified date of the `File`.
* @since v19.2.0, v18.13.0
*/
readonly lastModified: number;
}
export import atob = globalThis.atob;
export import btoa = globalThis.btoa;
import { Blob as NodeBlob } from "buffer";
// This conditional type will be the existing global Blob in a browser, or
// the copy below in a Node environment.
type __Blob = typeof globalThis extends { onmessage: any; Blob: any } ? {} : NodeBlob;
global {
namespace NodeJS {
export { BufferEncoding };
}
// Buffer class
type BufferEncoding =
| "ascii"
| "utf8"
| "utf-8"
| "utf16le"
| "utf-16le"
| "ucs2"
| "ucs-2"
| "base64"
| "base64url"
| "latin1"
| "binary"
| "hex";
type WithImplicitCoercion<T> =
| T
| {
valueOf(): T;
};
/**
* Raw data is stored in instances of the Buffer class.
* A Buffer is similar to an array of integers but corresponds to a raw memory allocation outside the V8 heap. A Buffer cannot be resized.
* Valid string encodings: 'ascii'|'utf8'|'utf16le'|'ucs2'(alias of 'utf16le')|'base64'|'base64url'|'binary'(deprecated)|'hex'
*/
interface BufferConstructor {
/**
* Allocates a new buffer containing the given {str}.
*
* @param str String to store in buffer.
* @param encoding encoding to use, optional. Default is 'utf8'
* @deprecated since v10.0.0 - Use `Buffer.from(string[, encoding])` instead.
*/
new(str: string, encoding?: BufferEncoding): Buffer;
/**
* Allocates a new buffer of {size} octets.
*
* @param size count of octets to allocate.
* @deprecated since v10.0.0 - Use `Buffer.alloc()` instead (also see `Buffer.allocUnsafe()`).
*/
new(size: number): Buffer;
/**
* Allocates a new buffer containing the given {array} of octets.
*
* @param array The octets to store.
* @deprecated since v10.0.0 - Use `Buffer.from(array)` instead.
*/
new(array: Uint8Array): Buffer;
/**
* Produces a Buffer backed by the same allocated memory as
* the given {ArrayBuffer}/{SharedArrayBuffer}.
*
* @param arrayBuffer The ArrayBuffer with which to share memory.
* @deprecated since v10.0.0 - Use `Buffer.from(arrayBuffer[, byteOffset[, length]])` instead.
*/
new(arrayBuffer: ArrayBuffer | SharedArrayBuffer): Buffer;
/**
* Allocates a new buffer containing the given {array} of octets.
*
* @param array The octets to store.
* @deprecated since v10.0.0 - Use `Buffer.from(array)` instead.
*/
new(array: readonly any[]): Buffer;
/**
* Copies the passed {buffer} data onto a new {Buffer} instance.
*
* @param buffer The buffer to copy.
* @deprecated since v10.0.0 - Use `Buffer.from(buf |
fer)` instead.
*/
new(buffer: Buffer): Buffer;
/**
* Allocates a new `Buffer` using an `array` of bytes in the range `0` – `255`.
* Array entries outside that range will be truncated to fit into it.
*
* ```js
* import { Buffer } from 'node:buffer';
*
* // Creates a new Buffer containing the UTF-8 bytes of the string 'buffer'.
* const buf = Buffer.from([0x62, 0x75, 0x66, 0x66, 0x65, 0x72]);
* ```
*
* If `array` is an `Array`\-like object (that is, one with a `length` property of
* type `number`), it is treated as if it is an array, unless it is a `Buffer` or
* a `Uint8Array`. This means all other `TypedArray` variants get treated as an`Array`. To create a `Buffer` from the bytes backing a `TypedArray`, use `Buffer.copyBytesFrom()`.
*
* A `TypeError` will be thrown if `array` is not an `Array` or another type
* appropriate for `Buffer.from()` variants.
*
* `Buffer.from(array)` and `Buffer.from(string)` may also use the internal`Buffer` pool like `Buffer.allocUnsafe()` does.
* @since v5.10.0
*/
from(
arrayBuffer: WithImplicitCoercion<ArrayBuffer | SharedArrayBuffer>,
byteOffset?: number,
length?: number,
): Buffer;
/**
* Creates a new Buffer using the passed {data}
* @param data data to create a new Buffer
*/
from(data: Uint8Array | readonly number[]): Buffer;
from(data: WithImplicitCoercion<Uint8Array | readonly number[] | string>): Buffer;
/**
* Creates a new Buffer containing the given JavaScript string {str}.
* If provided, the {encoding} parameter identifies the character encoding.
* If not provided, {encoding} defaults to 'utf8'.
*/
from(
str:
| WithImplicitCoercion<string>
| {
[Symbol.toPrimitive](hint: "string"): string;
},
encoding?: BufferEncoding,
): Buffer;
/**
* Creates a new Buffer using the passed {data}
* @param values to create a new Buffer
*/
of(...items: number[]): Buffer;
/**
* Returns `true` if `obj` is a `Buffer`, `false` otherwise.
*
* ```js
* import { Buffer } from 'node:buffer';
*
* Buffer.isBuffer(Buffer.alloc(10)); // true
* Buffer.isBuffer(Buffer.from('foo')); // true
* Buffer.isBuffer('a string'); // false
* Buffer.isBuffer([]); // false
* Buffer.isBuffer(new Uint8Array(1024)); // false
* ```
* @since v0.1.101
*/
isBuffer(obj: any): obj is Buffer;
/**
* Returns `true` if `encoding` is the name of a supported character encoding,
* or `false` otherwise.
*
* ```js
* import { Buffer } from 'node:buffer';
*
* console.log(Buffer.isEncoding('utf8'));
* // Prints: true
*
* console.log(Buffer.isEncoding('hex'));
* // Prints: true
*
* console.log(Buffer.isEncoding('utf/8'));
* // Prints: false
*
* console.log(Buffer.isEncoding(''));
* // Prints: false
* ```
* @since v0.9.1
* @param encoding A character encoding name to check.
*/
isEncoding(encoding: string): encoding is BufferEncoding;
/**
* Returns the byte |
length of a string when encoded using `encoding`.
* This is not the same as [`String.prototype.length`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/String/length), which does not account
* for the encoding that is used to convert the string into bytes.
*
* For `'base64'`, `'base64url'`, and `'hex'`, this function assumes valid input.
* For strings that contain non-base64/hex-encoded data (e.g. whitespace), the
* return value might be greater than the length of a `Buffer` created from the
* string.
*
* ```js
* import { Buffer } from 'node:buffer';
*
* const str = '\u00bd + \u00bc = \u00be';
*
* console.log(`${str}: ${str.length} characters, ` +
* `${Buffer.byteLength(str, 'utf8')} bytes`);
* // Prints: ½ + ¼ = ¾: 9 characters, 12 bytes
* ```
*
* When `string` is a
* `Buffer`/[`DataView`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/DataView)/[`TypedArray`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/-
* Reference/Global_Objects/TypedArray)/[`ArrayBuffer`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/ArrayBuffer)/[`SharedArrayBuffer`](https://develop-
* er.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/SharedArrayBuffer), the byte length as reported by `.byteLength`is returned.
* @since v0.1.90
* @param string A value to calculate the length of.
* @param [encoding='utf8'] If `string` is a string, this is its encoding.
* @return The number of bytes contained within `string`.
*/
byteLength(
string: string | NodeJS.ArrayBufferView | ArrayBuffer | SharedArrayBuffer,
encoding?: BufferEncoding,
): number;
/**
* Returns a new `Buffer` which is the result of concatenating all the `Buffer`instances in the `list` together.
*
* If the list has no items, or if the `totalLength` is 0, then a new zero-length`Buffer` is returned.
*
* If `totalLength` is not provided, it is calculated from the `Buffer` instances
* in `list` by adding their lengths.
*
* If `totalLength` is provided, it is coerced to an unsigned integer. If the
* combined length of the `Buffer`s in `list` exceeds `totalLength`, the result is
* truncated to `totalLength`.
*
* ```js
* import { Buffer } from 'node:buffer';
*
* // Create a single `Buffer` from a list of three `Buffer` instances.
*
* const buf1 = Buffer.alloc(10);
* const buf2 = Buffer.alloc(14);
* const buf3 = Buffer.alloc(18);
* const totalLength = buf1.length + buf2.length + buf3.length;
*
* console.log(totalLength);
* // Prints: 42
*
* const bufA = Buffer.concat([buf1, buf2, buf3], totalLength);
*
* console.log(bufA);
* // Prints: <Buffer 00 00 00 00 ...>
* console.log(bufA.length);
* // Prints: 42
* ```
*
* `Buffer.concat()` may also use the internal `Buffer` pool like `Buffer.allocUnsafe()` does.
* @since v0.7.11
* @param list List of `Buffer` or {@link Uint8Array} instances to concatenate.
* @param totalLength Total length of the `Buffer` instances in `list` when concatenated.
*/
concat(list: readonly Uint8Array[], totalLength?: number): Buffer;
/**
|
* Copies the underlying memory of `view` into a new `Buffer`.
*
* ```js
* const u16 = new Uint16Array([0, 0xffff]);
* const buf = Buffer.copyBytesFrom(u16, 1, 1);
* u16[1] = 0;
* console.log(buf.length); // 2
* console.log(buf[0]); // 255
* console.log(buf[1]); // 255
* ```
* @since v19.8.0
* @param view The {TypedArray} to copy.
* @param [offset=': 0'] The starting offset within `view`.
* @param [length=view.length - offset] The number of elements from `view` to copy.
*/
copyBytesFrom(view: NodeJS.TypedArray, offset?: number, length?: number): Buffer;
/**
* Compares `buf1` to `buf2`, typically for the purpose of sorting arrays of`Buffer` instances. This is equivalent to calling `buf1.compare(buf2)`.
*
* ```js
* import { Buffer } from 'node:buffer';
*
* const buf1 = Buffer.from('1234');
* const buf2 = Buffer.from('0123');
* const arr = [buf1, buf2];
*
* console.log(arr.sort(Buffer.compare));
* // Prints: [ <Buffer 30 31 32 33>, <Buffer 31 32 33 34> ]
* // (This result is equal to: [buf2, buf1].)
* ```
* @since v0.11.13
* @return Either `-1`, `0`, or `1`, depending on the result of the comparison. See `compare` for details.
*/
compare(buf1: Uint8Array, buf2: Uint8Array): -1 | 0 | 1;
/**
* Allocates a new `Buffer` of `size` bytes. If `fill` is `undefined`, the`Buffer` will be zero-filled.
*
* ```js
* import { Buffer } from 'node:buffer';
*
* const buf = Buffer.alloc(5);
*
* console.log(buf);
* // Prints: <Buffer 00 00 00 00 00>
* ```
*
* If `size` is larger than {@link constants.MAX_LENGTH} or smaller than 0, `ERR_OUT_OF_RANGE` is thrown.
*
* If `fill` is specified, the allocated `Buffer` will be initialized by calling `buf.fill(fill)`.
*
* ```js
* import { Buffer } from 'node:buffer';
*
* const buf = Buffer.alloc(5, 'a');
*
* console.log(buf);
* // Prints: <Buffer 61 61 61 61 61>
* ```
*
* If both `fill` and `encoding` are specified, the allocated `Buffer` will be
* initialized by calling `buf.fill(fill, encoding)`.
*
* ```js
* import { Buffer } from 'node:buffer';
*
* const buf = Buffer.alloc(11, 'aGVsbG8gd29ybGQ=', 'base64');
*
* console.log(buf);
* // Prints: <Buffer 68 65 6c 6c 6f 20 77 6f 72 6c 64>
* ```
*
* Calling `Buffer.alloc()` can be measurably slower than the alternative `Buffer.allocUnsafe()` but ensures that the newly created `Buffer` instance
* contents will never contain sensitive data from previous allocations, including
* data that might not have been allocated for `Buffer`s.
*
* A `TypeError` will be thrown if `size` is not a number.
* @since v5.10.0
* @param size The desired length of the new `Buffer`.
* @param [fill=0] A value to pre-fill the new `Buffer` with.
* @param [encoding='utf8'] If `fill` is a string, this is its encoding.
*/
alloc(size: number, fill?: string | Uint8Array | number, encoding?: BufferEncoding): Buffer;
/**
* Allocates a new `Buffer` of `size` bytes. If `size` is larger than {@link constants.MAX_LENGTH} or smaller than 0, `ERR_O |
UT_OF_RANGE` is thrown.
*
* The underlying memory for `Buffer` instances created in this way is _not_
* _initialized_. The contents of the newly created `Buffer` are unknown and _may contain sensitive data_. Use `Buffer.alloc()` instead to initialize`Buffer` instances with zeroes.
*
* ```js
* import { Buffer } from 'node:buffer';
*
* const buf = Buffer.allocUnsafe(10);
*
* console.log(buf);
* // Prints (contents may vary): <Buffer a0 8b 28 3f 01 00 00 00 50 32>
*
* buf.fill(0);
*
* console.log(buf);
* // Prints: <Buffer 00 00 00 00 00 00 00 00 00 00>
* ```
*
* A `TypeError` will be thrown if `size` is not a number.
*
* The `Buffer` module pre-allocates an internal `Buffer` instance of
* size `Buffer.poolSize` that is used as a pool for the fast allocation of new`Buffer` instances created using `Buffer.allocUnsafe()`, `Buffer.from(array)`,
* and `Buffer.concat()` only when `size` is less than`Buffer.poolSize >>> 1` (floor of `Buffer.poolSize` divided by two).
*
* Use of this pre-allocated internal memory pool is a key difference between
* calling `Buffer.alloc(size, fill)` vs. `Buffer.allocUnsafe(size).fill(fill)`.
* Specifically, `Buffer.alloc(size, fill)` will _never_ use the internal `Buffer`pool, while `Buffer.allocUnsafe(size).fill(fill)`_will_ use the internal`Buffer` pool if `size` is less
* than or equal to half `Buffer.poolSize`. The
* difference is subtle but can be important when an application requires the
* additional performance that `Buffer.allocUnsafe()` provides.
* @since v5.10.0
* @param size The desired length of the new `Buffer`.
*/
allocUnsafe(size: number): Buffer;
/**
* Allocates a new `Buffer` of `size` bytes. If `size` is larger than {@link constants.MAX_LENGTH} or smaller than 0, `ERR_OUT_OF_RANGE` is thrown. A zero-length `Buffer` is created if
* `size` is 0.
*
* The underlying memory for `Buffer` instances created in this way is _not_
* _initialized_. The contents of the newly created `Buffer` are unknown and _may contain sensitive data_. Use `buf.fill(0)` to initialize
* such `Buffer` instances with zeroes.
*
* When using `Buffer.allocUnsafe()` to allocate new `Buffer` instances,
* allocations under 4 KiB are sliced from a single pre-allocated `Buffer`. This
* allows applications to avoid the garbage collection overhead of creating many
* individually allocated `Buffer` instances. This approach improves both
* performance and memory usage by eliminating the need to track and clean up as
* many individual `ArrayBuffer` objects.
*
* However, in the case where a developer may need to retain a small chunk of
* memory from a pool for an indeterminate amount of time, it may be appropriate
* to create an un-pooled `Buffer` instance using `Buffer.allocUnsafeSlow()` and
* then copying out the relevant bits.
*
* ```js
* import { Buffer } from 'node:buffer';
*
* // Need to keep around a few small chunks of memory.
* const store = [];
*
* socket.on('readable', () => {
* let data;
* while (null !== (data = readable.read())) {
* // Allocate for retained data.
* const sb = Buffer.allocUnsafeSlow(10);
*
* // Copy the data into the new allocation.
|
* data.copy(sb, 0, 0, 10);
*
* store.push(sb);
* }
* });
* ```
*
* A `TypeError` will be thrown if `size` is not a number.
* @since v5.12.0
* @param size The desired length of the new `Buffer`.
*/
allocUnsafeSlow(size: number): Buffer;
/**
* This is the size (in bytes) of pre-allocated internal `Buffer` instances used
* for pooling. This value may be modified.
* @since v0.11.3
*/
poolSize: number;
}
interface Buffer extends Uint8Array {
/**
* Writes `string` to `buf` at `offset` according to the character encoding in`encoding`. The `length` parameter is the number of bytes to write. If `buf` did
* not contain enough space to fit the entire string, only part of `string` will be
* written. However, partially encoded characters will not be written.
*
* ```js
* import { Buffer } from 'node:buffer';
*
* const buf = Buffer.alloc(256);
*
* const len = buf.write('\u00bd + \u00bc = \u00be', 0);
*
* console.log(`${len} bytes: ${buf.toString('utf8', 0, len)}`);
* // Prints: 12 bytes: ½ + ¼ = ¾
*
* const buffer = Buffer.alloc(10);
*
* const length = buffer.write('abcd', 8);
*
* console.log(`${length} bytes: ${buffer.toString('utf8', 8, 10)}`);
* // Prints: 2 bytes : ab
* ```
* @since v0.1.90
* @param string String to write to `buf`.
* @param [offset=0] Number of bytes to skip before starting to write `string`.
* @param [length=buf.length - offset] Maximum number of bytes to write (written bytes will not exceed `buf.length - offset`).
* @param [encoding='utf8'] The character encoding of `string`.
* @return Number of bytes written.
*/
write(string: string, encoding?: BufferEncoding): number;
write(string: string, offset: number, encoding?: BufferEncoding): number;
write(string: string, offset: number, length: number, encoding?: BufferEncoding): number;
/**
* Decodes `buf` to a string according to the specified character encoding in`encoding`. `start` and `end` may be passed to decode only a subset of `buf`.
*
* If `encoding` is `'utf8'` and a byte sequence in the input is not valid UTF-8,
* then each invalid byte is replaced with the replacement character `U+FFFD`.
*
* The maximum length of a string instance (in UTF-16 code units) is available
* as {@link constants.MAX_STRING_LENGTH}.
*
* ```js
* import { Buffer } from 'node:buffer';
*
* const buf1 = Buffer.allocUnsafe(26);
*
* for (let i = 0; i < 26; i++) {
* // 97 is the decimal ASCII value for 'a'.
* buf1[i] = i + 97;
* }
*
* console.log(buf1.toString('utf8'));
* // Prints: abcdefghijklmnopqrstuvwxyz
* console.log(buf1.toString('utf8', 0, 5));
* // Prints: abcde
*
* const buf2 = Buffer.from('tést');
*
* console.log(buf2.toString('hex'));
* // Prints: 74c3a97374
* console.log(buf2.toString('utf8', 0, 3));
* // Prints: té
* console.log(buf2.toString(undefined, 0, 3));
* // Prints: té
* ```
* @since v0.1.90
* @param [encoding='utf8'] The character encoding to use.
* @param |
[start=0] The byte offset to start decoding at.
* @param [end=buf.length] The byte offset to stop decoding at (not inclusive).
*/
toString(encoding?: BufferEncoding, start?: number, end?: number): string;
/**
* Returns a JSON representation of `buf`. [`JSON.stringify()`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/JSON/stringify) implicitly calls
* this function when stringifying a `Buffer` instance.
*
* `Buffer.from()` accepts objects in the format returned from this method.
* In particular, `Buffer.from(buf.toJSON())` works like `Buffer.from(buf)`.
*
* ```js
* import { Buffer } from 'node:buffer';
*
* const buf = Buffer.from([0x1, 0x2, 0x3, 0x4, 0x5]);
* const json = JSON.stringify(buf);
*
* console.log(json);
* // Prints: {"type":"Buffer","data":[1,2,3,4,5]}
*
* const copy = JSON.parse(json, (key, value) => {
* return value && value.type === 'Buffer' ?
* Buffer.from(value) :
* value;
* });
*
* console.log(copy);
* // Prints: <Buffer 01 02 03 04 05>
* ```
* @since v0.9.2
*/
toJSON(): {
type: "Buffer";
data: number[];
};
/**
* Returns `true` if both `buf` and `otherBuffer` have exactly the same bytes,`false` otherwise. Equivalent to `buf.compare(otherBuffer) === 0`.
*
* ```js
* import { Buffer } from 'node:buffer';
*
* const buf1 = Buffer.from('ABC');
* const buf2 = Buffer.from('414243', 'hex');
* const buf3 = Buffer.from('ABCD');
*
* console.log(buf1.equals(buf2));
* // Prints: true
* console.log(buf1.equals(buf3));
* // Prints: false
* ```
* @since v0.11.13
* @param otherBuffer A `Buffer` or {@link Uint8Array} with which to compare `buf`.
*/
equals(otherBuffer: Uint8Array): boolean;
/**
* Compares `buf` with `target` and returns a number indicating whether `buf`comes before, after, or is the same as `target` in sort order.
* Comparison is based on the actual sequence of bytes in each `Buffer`.
*
* * `0` is returned if `target` is the same as `buf`
* * `1` is returned if `target` should come _before_`buf` when sorted.
* * `-1` is returned if `target` should come _after_`buf` when sorted.
*
* ```js
* import { Buffer } from 'node:buffer';
*
* const buf1 = Buffer.from('ABC');
* const buf2 = Buffer.from('BCD');
* const buf3 = Buffer.from('ABCD');
*
* console.log(buf1.compare(buf1));
* // Prints: 0
* console.log(buf1.compare(buf2));
* // Prints: -1
* console.log(buf1.compare(buf3));
* // Prints: -1
* console.log(buf2.compare(buf1));
* // Prints: 1
* console.log(buf2.compare(buf3));
* // Prints: 1
* console.log([buf1, buf2, buf3].sort(Buffer.compare));
* // Prints: [ <Buffer 41 42 43>, <Buffer 41 42 43 44>, <Buffer 42 43 44> ]
* // (This result is equal to: [buf1, buf3, buf2].)
* ```
*
* The optional `targetStart`, `targetEnd`, `sourceStart`, and `sourceEnd`arguments can be used to limit the comparison to specific ranges within `target`and `buf` respectively.
*
* ```js
|
* import { Buffer } from 'node:buffer';
*
* const buf1 = Buffer.from([1, 2, 3, 4, 5, 6, 7, 8, 9]);
* const buf2 = Buffer.from([5, 6, 7, 8, 9, 1, 2, 3, 4]);
*
* console.log(buf1.compare(buf2, 5, 9, 0, 4));
* // Prints: 0
* console.log(buf1.compare(buf2, 0, 6, 4));
* // Prints: -1
* console.log(buf1.compare(buf2, 5, 6, 5));
* // Prints: 1
* ```
*
* `ERR_OUT_OF_RANGE` is thrown if `targetStart < 0`, `sourceStart < 0`,`targetEnd > target.byteLength`, or `sourceEnd > source.byteLength`.
* @since v0.11.13
* @param target A `Buffer` or {@link Uint8Array} with which to compare `buf`.
* @param [targetStart=0] The offset within `target` at which to begin comparison.
* @param [targetEnd=target.length] The offset within `target` at which to end comparison (not inclusive).
* @param [sourceStart=0] The offset within `buf` at which to begin comparison.
* @param [sourceEnd=buf.length] The offset within `buf` at which to end comparison (not inclusive).
*/
compare(
target: Uint8Array,
targetStart?: number,
targetEnd?: number,
sourceStart?: number,
sourceEnd?: number,
): -1 | 0 | 1;
/**
* Copies data from a region of `buf` to a region in `target`, even if the `target`memory region overlaps with `buf`.
*
* [`TypedArray.prototype.set()`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/TypedArray/set) performs the same operation, and is available
* for all TypedArrays, including Node.js `Buffer`s, although it takes
* different function arguments.
*
* ```js
* import { Buffer } from 'node:buffer';
*
* // Create two `Buffer` instances.
* const buf1 = Buffer.allocUnsafe(26);
* const buf2 = Buffer.allocUnsafe(26).fill('!');
*
* for (let i = 0; i < 26; i++) {
* // 97 is the decimal ASCII value for 'a'.
* buf1[i] = i + 97;
* }
*
* // Copy `buf1` bytes 16 through 19 into `buf2` starting at byte 8 of `buf2`.
* buf1.copy(buf2, 8, 16, 20);
* // This is equivalent to:
* // buf2.set(buf1.subarray(16, 20), 8);
*
* console.log(buf2.toString('ascii', 0, 25));
* // Prints: !!!!!!!!qrst!!!!!!!!!!!!!
* ```
*
* ```js
* import { Buffer } from 'node:buffer';
*
* // Create a `Buffer` and copy data from one region to an overlapping region
* // within the same `Buffer`.
*
* const buf = Buffer.allocUnsafe(26);
*
* for (let i = 0; i < 26; i++) {
* // 97 is the decimal ASCII value for 'a'.
* buf[i] = i + 97;
* }
*
* buf.copy(buf, 0, 4, 10);
*
* console.log(buf.toString());
* // Prints: efghijghijklmnopqrstuvwxyz
* ```
* @since v0.1.90
* @param target A `Buffer` or {@link Uint8Array} to copy into.
* @param [targetStart=0] The offset within `target` at which to begin writing.
* @param [sourceStart=0] The offset within `buf` from which to begin copying.
* @param [sourceEnd=buf.length] The offset within `buf` at which to stop copying (not inclusive).
* @return The number of bytes copied.
*/
copy(target: Uint8Array, targetStart?: number, sourceStart?: number, sourceEnd?: number): number;
|
/**
* Returns a new `Buffer` that references the same memory as the original, but
* offset and cropped by the `start` and `end` indices.
*
* This method is not compatible with the `Uint8Array.prototype.slice()`,
* which is a superclass of `Buffer`. To copy the slice, use`Uint8Array.prototype.slice()`.
*
* ```js
* import { Buffer } from 'node:buffer';
*
* const buf = Buffer.from('buffer');
*
* const copiedBuf = Uint8Array.prototype.slice.call(buf);
* copiedBuf[0]++;
* console.log(copiedBuf.toString());
* // Prints: cuffer
*
* console.log(buf.toString());
* // Prints: buffer
*
* // With buf.slice(), the original buffer is modified.
* const notReallyCopiedBuf = buf.slice();
* notReallyCopiedBuf[0]++;
* console.log(notReallyCopiedBuf.toString());
* // Prints: cuffer
* console.log(buf.toString());
* // Also prints: cuffer (!)
* ```
* @since v0.3.0
* @deprecated Use `subarray` instead.
* @param [start=0] Where the new `Buffer` will start.
* @param [end=buf.length] Where the new `Buffer` will end (not inclusive).
*/
slice(start?: number, end?: number): Buffer;
/**
* Returns a new `Buffer` that references the same memory as the original, but
* offset and cropped by the `start` and `end` indices.
*
* Specifying `end` greater than `buf.length` will return the same result as
* that of `end` equal to `buf.length`.
*
* This method is inherited from [`TypedArray.prototype.subarray()`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/TypedArray/subarray).
*
* Modifying the new `Buffer` slice will modify the memory in the original `Buffer`because the allocated memory of the two objects overlap.
*
* ```js
* import { Buffer } from 'node:buffer';
*
* // Create a `Buffer` with the ASCII alphabet, take a slice, and modify one byte
* // from the original `Buffer`.
*
* const buf1 = Buffer.allocUnsafe(26);
*
* for (let i = 0; i < 26; i++) {
* // 97 is the decimal ASCII value for 'a'.
* buf1[i] = i + 97;
* }
*
* const buf2 = buf1.subarray(0, 3);
*
* console.log(buf2.toString('ascii', 0, buf2.length));
* // Prints: abc
*
* buf1[0] = 33;
*
* console.log(buf2.toString('ascii', 0, buf2.length));
* // Prints: !bc
* ```
*
* Specifying negative indexes causes the slice to be generated relative to the
* end of `buf` rather than the beginning.
*
* ```js
* import { Buffer } from 'node:buffer';
*
* const buf = Buffer.from('buffer');
*
* console.log(buf.subarray(-6, -1).toString());
* // Prints: buffe
* // (Equivalent to buf.subarray(0, 5).)
*
* console.log(buf.subarray(-6, -2).toString());
* // Prints: buff
* // (Equivalent to buf.subarray(0, 4).)
*
* console.log(buf.subarray(-5, -2).toString());
* // Prints: uff
* // (Equivalent to buf.subarray(1, 4).)
* ```
* @since v3.0.0
* @param [start=0] Where the new `Buffer` will start.
* @param [end=buf.length] Where th |
e new `Buffer` will end (not inclusive).
*/
subarray(start?: number, end?: number): Buffer;
/**
* Writes `value` to `buf` at the specified `offset` as big-endian.
*
* `value` is interpreted and written as a two's complement signed integer.
*
* ```js
* import { Buffer } from 'node:buffer';
*
* const buf = Buffer.allocUnsafe(8);
*
* buf.writeBigInt64BE(0x0102030405060708n, 0);
*
* console.log(buf);
* // Prints: <Buffer 01 02 03 04 05 06 07 08>
* ```
* @since v12.0.0, v10.20.0
* @param value Number to be written to `buf`.
* @param [offset=0] Number of bytes to skip before starting to write. Must satisfy: `0 <= offset <= buf.length - 8`.
* @return `offset` plus the number of bytes written.
*/
writeBigInt64BE(value: bigint, offset?: number): number;
/**
* Writes `value` to `buf` at the specified `offset` as little-endian.
*
* `value` is interpreted and written as a two's complement signed integer.
*
* ```js
* import { Buffer } from 'node:buffer';
*
* const buf = Buffer.allocUnsafe(8);
*
* buf.writeBigInt64LE(0x0102030405060708n, 0);
*
* console.log(buf);
* // Prints: <Buffer 08 07 06 05 04 03 02 01>
* ```
* @since v12.0.0, v10.20.0
* @param value Number to be written to `buf`.
* @param [offset=0] Number of bytes to skip before starting to write. Must satisfy: `0 <= offset <= buf.length - 8`.
* @return `offset` plus the number of bytes written.
*/
writeBigInt64LE(value: bigint, offset?: number): number;
/**
* Writes `value` to `buf` at the specified `offset` as big-endian.
*
* This function is also available under the `writeBigUint64BE` alias.
*
* ```js
* import { Buffer } from 'node:buffer';
*
* const buf = Buffer.allocUnsafe(8);
*
* buf.writeBigUInt64BE(0xdecafafecacefaden, 0);
*
* console.log(buf);
* // Prints: <Buffer de ca fa fe ca ce fa de>
* ```
* @since v12.0.0, v10.20.0
* @param value Number to be written to `buf`.
* @param [offset=0] Number of bytes to skip before starting to write. Must satisfy: `0 <= offset <= buf.length - 8`.
* @return `offset` plus the number of bytes written.
*/
writeBigUInt64BE(value: bigint, offset?: number): number;
/**
* @alias Buffer.writeBigUInt64BE
* @since v14.10.0, v12.19.0
*/
writeBigUint64BE(value: bigint, offset?: number): number;
/**
* Writes `value` to `buf` at the specified `offset` as little-endian
*
* ```js
* import { Buffer } from 'node:buffer';
*
* const buf = Buffer.allocUnsafe(8);
*
* buf.writeBigUInt64LE(0xdecafafecacefaden, 0);
*
* console.log(buf);
* // Prints: <Buffer de fa ce ca fe fa ca de>
* ```
*
* This function is also available under the `writeBigUint64LE` alias.
* @since v12.0.0, v10.20.0
* @param value Number to be written to `buf`.
* @param [offset=0] Number of bytes to skip before starting to write. Must satisfy: `0 <= offset <= buf.length - 8`.
* @return `offset` plus the number of bytes written.
*/
writeBigUInt64LE( |
value: bigint, offset?: number): number;
/**
* @alias Buffer.writeBigUInt64LE
* @since v14.10.0, v12.19.0
*/
writeBigUint64LE(value: bigint, offset?: number): number;
/**
* 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.
*
* ```js
* import { Buffer } from 'node:buffer';
*
* const buf = Buffer.allocUnsafe(6);
*
* buf.writeUIntLE(0x1234567890ab, 0, 6);
*
* console.log(buf);
* // Prints: <Buffer ab 90 78 56 34 12>
* ```
* @since v0.5.5
* @param value Number to be written to `buf`.
* @param offset Number of bytes to skip before starting to write. Must satisfy `0 <= offset <= buf.length - byteLength`.
* @param byteLength Number of bytes to write. Must satisfy `0 < byteLength <= 6`.
* @return `offset` plus the number of bytes written.
*/
writeUIntLE(value: number, offset: number, byteLength: number): number;
/**
* @alias Buffer.writeUIntLE
* @since v14.9.0, v12.19.0
*/
writeUintLE(value: number, offset: number, byteLength: number): number;
/**
* 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.
*
* ```js
* import { Buffer } from 'node:buffer';
*
* const buf = Buffer.allocUnsafe(6);
*
* buf.writeUIntBE(0x1234567890ab, 0, 6);
*
* console.log(buf);
* // Prints: <Buffer 12 34 56 78 90 ab>
* ```
* @since v0.5.5
* @param value Number to be written to `buf`.
* @param offset Number of bytes to skip before starting to write. Must satisfy `0 <= offset <= buf.length - byteLength`.
* @param byteLength Number of bytes to write. Must satisfy `0 < byteLength <= 6`.
* @return `offset` plus the number of bytes written.
*/
writeUIntBE(value: number, offset: number, byteLength: number): number;
/**
* @alias Buffer.writeUIntBE
* @since v14.9.0, v12.19.0
*/
writeUintBE(value: number, offset: number, byteLength: number): number;
/**
* 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.
*
* ```js
* import { Buffer } from 'node:buffer';
*
* const buf = Buffer.allocUnsafe(6);
*
* buf.writeIntLE(0x1234567890ab, 0, 6);
*
* console.log(buf);
* // Prints: <Buffer ab 90 78 56 34 12>
* ```
* @since v0.11.15
* @param value Number to be written to `buf`.
* @param offset Number of bytes to skip before starting to write. Must satisfy `0 <= offset <= buf.length - byteLength`.
* @param byteLength Number of bytes to write. Must satisfy `0 < byteLength <= 6`.
* @return `offset` plus the number of bytes written.
*/
writeIntLE(value: number, offset: numbe |
r, byteLength: number): number;
/**
* 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.
*
* ```js
* import { Buffer } from 'node:buffer';
*
* const buf = Buffer.allocUnsafe(6);
*
* buf.writeIntBE(0x1234567890ab, 0, 6);
*
* console.log(buf);
* // Prints: <Buffer 12 34 56 78 90 ab>
* ```
* @since v0.11.15
* @param value Number to be written to `buf`.
* @param offset Number of bytes to skip before starting to write. Must satisfy `0 <= offset <= buf.length - byteLength`.
* @param byteLength Number of bytes to write. Must satisfy `0 < byteLength <= 6`.
* @return `offset` plus the number of bytes written.
*/
writeIntBE(value: number, offset: number, byteLength: number): number;
/**
* Reads an unsigned, big-endian 64-bit integer from `buf` at the specified`offset`.
*
* This function is also available under the `readBigUint64BE` alias.
*
* ```js
* import { Buffer } from 'node:buffer';
*
* const buf = Buffer.from([0x00, 0x00, 0x00, 0x00, 0xff, 0xff, 0xff, 0xff]);
*
* console.log(buf.readBigUInt64BE(0));
* // Prints: 4294967295n
* ```
* @since v12.0.0, v10.20.0
* @param [offset=0] Number of bytes to skip before starting to read. Must satisfy: `0 <= offset <= buf.length - 8`.
*/
readBigUInt64BE(offset?: number): bigint;
/**
* @alias Buffer.readBigUInt64BE
* @since v14.10.0, v12.19.0
*/
readBigUint64BE(offset?: number): bigint;
/**
* Reads an unsigned, little-endian 64-bit integer from `buf` at the specified`offset`.
*
* This function is also available under the `readBigUint64LE` alias.
*
* ```js
* import { Buffer } from 'node:buffer';
*
* const buf = Buffer.from([0x00, 0x00, 0x00, 0x00, 0xff, 0xff, 0xff, 0xff]);
*
* console.log(buf.readBigUInt64LE(0));
* // Prints: 18446744069414584320n
* ```
* @since v12.0.0, v10.20.0
* @param [offset=0] Number of bytes to skip before starting to read. Must satisfy: `0 <= offset <= buf.length - 8`.
*/
readBigUInt64LE(offset?: number): bigint;
/**
* @alias Buffer.readBigUInt64LE
* @since v14.10.0, v12.19.0
*/
readBigUint64LE(offset?: number): bigint;
/**
* Reads a signed, big-endian 64-bit integer from `buf` at the specified `offset`.
*
* Integers read from a `Buffer` are interpreted as two's complement signed
* values.
* @since v12.0.0, v10.20.0
* @param [offset=0] Number of bytes to skip before starting to read. Must satisfy: `0 <= offset <= buf.length - 8`.
*/
readBigInt64BE(offset?: number): bigint;
/**
* Reads a signed, little-endian 64-bit integer from `buf` at the specified`offset`.
*
* Integers read from a `Buffer` are interpreted as two's complement signed
* values.
* @since v12.0.0, v10.20.0
* @param [offset=0] Number of bytes to skip before starting to read. Must satisfy: `0 <= offset <= buf.length - 8`.
*/
readBigInt64LE(offset?: number): bigint;
/**
* Reads `byteLength` number |
of bytes from `buf` at the specified `offset`and interprets the result as an unsigned, little-endian integer supporting
* up to 48 bits of accuracy.
*
* This function is also available under the `readUintLE` alias.
*
* ```js
* import { Buffer } from 'node:buffer';
*
* const buf = Buffer.from([0x12, 0x34, 0x56, 0x78, 0x90, 0xab]);
*
* console.log(buf.readUIntLE(0, 6).toString(16));
* // Prints: ab9078563412
* ```
* @since v0.11.15
* @param offset Number of bytes to skip before starting to read. Must satisfy `0 <= offset <= buf.length - byteLength`.
* @param byteLength Number of bytes to read. Must satisfy `0 < byteLength <= 6`.
*/
readUIntLE(offset: number, byteLength: number): number;
/**
* @alias Buffer.readUIntLE
* @since v14.9.0, v12.19.0
*/
readUintLE(offset: number, byteLength: number): number;
/**
* Reads `byteLength` number of bytes from `buf` at the specified `offset`and interprets the result as an unsigned big-endian integer supporting
* up to 48 bits of accuracy.
*
* This function is also available under the `readUintBE` alias.
*
* ```js
* import { Buffer } from 'node:buffer';
*
* const buf = Buffer.from([0x12, 0x34, 0x56, 0x78, 0x90, 0xab]);
*
* console.log(buf.readUIntBE(0, 6).toString(16));
* // Prints: 1234567890ab
* console.log(buf.readUIntBE(1, 6).toString(16));
* // Throws ERR_OUT_OF_RANGE.
* ```
* @since v0.11.15
* @param offset Number of bytes to skip before starting to read. Must satisfy `0 <= offset <= buf.length - byteLength`.
* @param byteLength Number of bytes to read. Must satisfy `0 < byteLength <= 6`.
*/
readUIntBE(offset: number, byteLength: number): number;
/**
* @alias Buffer.readUIntBE
* @since v14.9.0, v12.19.0
*/
readUintBE(offset: number, byteLength: number): number;
/**
* Reads `byteLength` number of bytes from `buf` at the specified `offset`and interprets the result as a little-endian, two's complement signed value
* supporting up to 48 bits of accuracy.
*
* ```js
* import { Buffer } from 'node:buffer';
*
* const buf = Buffer.from([0x12, 0x34, 0x56, 0x78, 0x90, 0xab]);
*
* console.log(buf.readIntLE(0, 6).toString(16));
* // Prints: -546f87a9cbee
* ```
* @since v0.11.15
* @param offset Number of bytes to skip before starting to read. Must satisfy `0 <= offset <= buf.length - byteLength`.
* @param byteLength Number of bytes to read. Must satisfy `0 < byteLength <= 6`.
*/
readIntLE(offset: number, byteLength: number): number;
/**
* Reads `byteLength` number of bytes from `buf` at the specified `offset`and interprets the result as a big-endian, two's complement signed value
* supporting up to 48 bits of accuracy.
*
* ```js
* import { Buffer } from 'node:buffer';
*
* const buf = Buffer.from([0x12, 0x34, 0x56, 0x78, 0x90, 0xab]);
*
* console.log(buf.readIntBE(0, 6).toString(16));
* // Prints: 1234567890ab
* console.log(buf.readIntBE(1, 6).toString(16));
* // Throws ERR_OUT_OF_RANGE.
* console.log(buf.readIntBE(1, 0).toString(16));
* // Throws ERR_OUT_OF_RANGE.
* ```
|
* @since v0.11.15
* @param offset Number of bytes to skip before starting to read. Must satisfy `0 <= offset <= buf.length - byteLength`.
* @param byteLength Number of bytes to read. Must satisfy `0 < byteLength <= 6`.
*/
readIntBE(offset: number, byteLength: number): number;
/**
* Reads an unsigned 8-bit integer from `buf` at the specified `offset`.
*
* This function is also available under the `readUint8` alias.
*
* ```js
* import { Buffer } from 'node:buffer';
*
* const buf = Buffer.from([1, -2]);
*
* console.log(buf.readUInt8(0));
* // Prints: 1
* console.log(buf.readUInt8(1));
* // Prints: 254
* console.log(buf.readUInt8(2));
* // Throws ERR_OUT_OF_RANGE.
* ```
* @since v0.5.0
* @param [offset=0] Number of bytes to skip before starting to read. Must satisfy `0 <= offset <= buf.length - 1`.
*/
readUInt8(offset?: number): number;
/**
* @alias Buffer.readUInt8
* @since v14.9.0, v12.19.0
*/
readUint8(offset?: number): number;
/**
* Reads an unsigned, little-endian 16-bit integer from `buf` at the specified`offset`.
*
* This function is also available under the `readUint16LE` alias.
*
* ```js
* import { Buffer } from 'node:buffer';
*
* const buf = Buffer.from([0x12, 0x34, 0x56]);
*
* console.log(buf.readUInt16LE(0).toString(16));
* // Prints: 3412
* console.log(buf.readUInt16LE(1).toString(16));
* // Prints: 5634
* console.log(buf.readUInt16LE(2).toString(16));
* // Throws ERR_OUT_OF_RANGE.
* ```
* @since v0.5.5
* @param [offset=0] Number of bytes to skip before starting to read. Must satisfy `0 <= offset <= buf.length - 2`.
*/
readUInt16LE(offset?: number): number;
/**
* @alias Buffer.readUInt16LE
* @since v14.9.0, v12.19.0
*/
readUint16LE(offset?: number): number;
/**
* Reads an unsigned, big-endian 16-bit integer from `buf` at the specified`offset`.
*
* This function is also available under the `readUint16BE` alias.
*
* ```js
* import { Buffer } from 'node:buffer';
*
* const buf = Buffer.from([0x12, 0x34, 0x56]);
*
* console.log(buf.readUInt16BE(0).toString(16));
* // Prints: 1234
* console.log(buf.readUInt16BE(1).toString(16));
* // Prints: 3456
* ```
* @since v0.5.5
* @param [offset=0] Number of bytes to skip before starting to read. Must satisfy `0 <= offset <= buf.length - 2`.
*/
readUInt16BE(offset?: number): number;
/**
* @alias Buffer.readUInt16BE
* @since v14.9.0, v12.19.0
*/
readUint16BE(offset?: number): number;
/**
* Reads an unsigned, little-endian 32-bit integer from `buf` at the specified`offset`.
*
* This function is also available under the `readUint32LE` alias.
*
* ```js
* import { Buffer } from 'node:buffer';
*
* const buf = Buffer.from([0x12, 0x34, 0x56, 0x78]);
*
* console.log(buf.readUInt32LE(0).toString(16));
* // Prints: 78563412
* console.log(buf.readUInt32LE(1).toString(16));
* // Throws ERR_OUT_OF_RANGE.
|
* ```
* @since v0.5.5
* @param [offset=0] Number of bytes to skip before starting to read. Must satisfy `0 <= offset <= buf.length - 4`.
*/
readUInt32LE(offset?: number): number;
/**
* @alias Buffer.readUInt32LE
* @since v14.9.0, v12.19.0
*/
readUint32LE(offset?: number): number;
/**
* Reads an unsigned, big-endian 32-bit integer from `buf` at the specified`offset`.
*
* This function is also available under the `readUint32BE` alias.
*
* ```js
* import { Buffer } from 'node:buffer';
*
* const buf = Buffer.from([0x12, 0x34, 0x56, 0x78]);
*
* console.log(buf.readUInt32BE(0).toString(16));
* // Prints: 12345678
* ```
* @since v0.5.5
* @param [offset=0] Number of bytes to skip before starting to read. Must satisfy `0 <= offset <= buf.length - 4`.
*/
readUInt32BE(offset?: number): number;
/**
* @alias Buffer.readUInt32BE
* @since v14.9.0, v12.19.0
*/
readUint32BE(offset?: number): number;
/**
* Reads a signed 8-bit integer from `buf` at the specified `offset`.
*
* Integers read from a `Buffer` are interpreted as two's complement signed values.
*
* ```js
* import { Buffer } from 'node:buffer';
*
* const buf = Buffer.from([-1, 5]);
*
* console.log(buf.readInt8(0));
* // Prints: -1
* console.log(buf.readInt8(1));
* // Prints: 5
* console.log(buf.readInt8(2));
* // Throws ERR_OUT_OF_RANGE.
* ```
* @since v0.5.0
* @param [offset=0] Number of bytes to skip before starting to read. Must satisfy `0 <= offset <= buf.length - 1`.
*/
readInt8(offset?: number): number;
/**
* Reads a signed, little-endian 16-bit integer from `buf` at the specified`offset`.
*
* Integers read from a `Buffer` are interpreted as two's complement signed values.
*
* ```js
* import { Buffer } from 'node:buffer';
*
* const buf = Buffer.from([0, 5]);
*
* console.log(buf.readInt16LE(0));
* // Prints: 1280
* console.log(buf.readInt16LE(1));
* // Throws ERR_OUT_OF_RANGE.
* ```
* @since v0.5.5
* @param [offset=0] Number of bytes to skip before starting to read. Must satisfy `0 <= offset <= buf.length - 2`.
*/
readInt16LE(offset?: number): number;
/**
* Reads a signed, big-endian 16-bit integer from `buf` at the specified `offset`.
*
* Integers read from a `Buffer` are interpreted as two's complement signed values.
*
* ```js
* import { Buffer } from 'node:buffer';
*
* const buf = Buffer.from([0, 5]);
*
* console.log(buf.readInt16BE(0));
* // Prints: 5
* ```
* @since v0.5.5
* @param [offset=0] Number of bytes to skip before starting to read. Must satisfy `0 <= offset <= buf.length - 2`.
*/
readInt16BE(offset?: number): number;
/**
* Reads a signed, little-endian 32-bit integer from `buf` at the specified`offset`.
*
* Integers read from a `Buffer` are interpreted as two's complement signed values.
*
* ```js
* import { Buffer } from 'node:buffer';
*
|
* const buf = Buffer.from([0, 0, 0, 5]);
*
* console.log(buf.readInt32LE(0));
* // Prints: 83886080
* console.log(buf.readInt32LE(1));
* // Throws ERR_OUT_OF_RANGE.
* ```
* @since v0.5.5
* @param [offset=0] Number of bytes to skip before starting to read. Must satisfy `0 <= offset <= buf.length - 4`.
*/
readInt32LE(offset?: number): number;
/**
* Reads a signed, big-endian 32-bit integer from `buf` at the specified `offset`.
*
* Integers read from a `Buffer` are interpreted as two's complement signed values.
*
* ```js
* import { Buffer } from 'node:buffer';
*
* const buf = Buffer.from([0, 0, 0, 5]);
*
* console.log(buf.readInt32BE(0));
* // Prints: 5
* ```
* @since v0.5.5
* @param [offset=0] Number of bytes to skip before starting to read. Must satisfy `0 <= offset <= buf.length - 4`.
*/
readInt32BE(offset?: number): number;
/**
* Reads a 32-bit, little-endian float from `buf` at the specified `offset`.
*
* ```js
* import { Buffer } from 'node:buffer';
*
* const buf = Buffer.from([1, 2, 3, 4]);
*
* console.log(buf.readFloatLE(0));
* // Prints: 1.539989614439558e-36
* console.log(buf.readFloatLE(1));
* // Throws ERR_OUT_OF_RANGE.
* ```
* @since v0.11.15
* @param [offset=0] Number of bytes to skip before starting to read. Must satisfy `0 <= offset <= buf.length - 4`.
*/
readFloatLE(offset?: number): number;
/**
* Reads a 32-bit, big-endian float from `buf` at the specified `offset`.
*
* ```js
* import { Buffer } from 'node:buffer';
*
* const buf = Buffer.from([1, 2, 3, 4]);
*
* console.log(buf.readFloatBE(0));
* // Prints: 2.387939260590663e-38
* ```
* @since v0.11.15
* @param [offset=0] Number of bytes to skip before starting to read. Must satisfy `0 <= offset <= buf.length - 4`.
*/
readFloatBE(offset?: number): number;
/**
* Reads a 64-bit, little-endian double from `buf` at the specified `offset`.
*
* ```js
* import { Buffer } from 'node:buffer';
*
* const buf = Buffer.from([1, 2, 3, 4, 5, 6, 7, 8]);
*
* console.log(buf.readDoubleLE(0));
* // Prints: 5.447603722011605e-270
* console.log(buf.readDoubleLE(1));
* // Throws ERR_OUT_OF_RANGE.
* ```
* @since v0.11.15
* @param [offset=0] Number of bytes to skip before starting to read. Must satisfy `0 <= offset <= buf.length - 8`.
*/
readDoubleLE(offset?: number): number;
/**
* Reads a 64-bit, big-endian double from `buf` at the specified `offset`.
*
* ```js
* import { Buffer } from 'node:buffer';
*
* const buf = Buffer.from([1, 2, 3, 4, 5, 6, 7, 8]);
*
* console.log(buf.readDoubleBE(0));
* // Prints: 8.20788039913184e-304
* ```
* @since v0.11.15
* @param [offset=0] Number of bytes to skip before starting to read. Must satisfy `0 <= offset <= buf.length - 8`.
*/
readDoubleBE(offset?: number): number;
reverse(): this;
/**
* Interprets `buf` as an array of unsigned 16-bit integers and swaps the
|
* byte order _in-place_. Throws `ERR_INVALID_BUFFER_SIZE` if `buf.length` is not a multiple of 2.
*
* ```js
* import { Buffer } from 'node:buffer';
*
* const buf1 = Buffer.from([0x1, 0x2, 0x3, 0x4, 0x5, 0x6, 0x7, 0x8]);
*
* console.log(buf1);
* // Prints: <Buffer 01 02 03 04 05 06 07 08>
*
* buf1.swap16();
*
* console.log(buf1);
* // Prints: <Buffer 02 01 04 03 06 05 08 07>
*
* const buf2 = Buffer.from([0x1, 0x2, 0x3]);
*
* buf2.swap16();
* // Throws ERR_INVALID_BUFFER_SIZE.
* ```
*
* One convenient use of `buf.swap16()` is to perform a fast in-place conversion
* between UTF-16 little-endian and UTF-16 big-endian:
*
* ```js
* import { Buffer } from 'node:buffer';
*
* const buf = Buffer.from('This is little-endian UTF-16', 'utf16le');
* buf.swap16(); // Convert to big-endian UTF-16 text.
* ```
* @since v5.10.0
* @return A reference to `buf`.
*/
swap16(): Buffer;
/**
* Interprets `buf` as an array of unsigned 32-bit integers and swaps the
* byte order _in-place_. Throws `ERR_INVALID_BUFFER_SIZE` if `buf.length` is not a multiple of 4.
*
* ```js
* import { Buffer } from 'node:buffer';
*
* const buf1 = Buffer.from([0x1, 0x2, 0x3, 0x4, 0x5, 0x6, 0x7, 0x8]);
*
* console.log(buf1);
* // Prints: <Buffer 01 02 03 04 05 06 07 08>
*
* buf1.swap32();
*
* console.log(buf1);
* // Prints: <Buffer 04 03 02 01 08 07 06 05>
*
* const buf2 = Buffer.from([0x1, 0x2, 0x3]);
*
* buf2.swap32();
* // Throws ERR_INVALID_BUFFER_SIZE.
* ```
* @since v5.10.0
* @return A reference to `buf`.
*/
swap32(): Buffer;
/**
* Interprets `buf` as an array of 64-bit numbers and swaps byte order _in-place_.
* Throws `ERR_INVALID_BUFFER_SIZE` if `buf.length` is not a multiple of 8.
*
* ```js
* import { Buffer } from 'node:buffer';
*
* const buf1 = Buffer.from([0x1, 0x2, 0x3, 0x4, 0x5, 0x6, 0x7, 0x8]);
*
* console.log(buf1);
* // Prints: <Buffer 01 02 03 04 05 06 07 08>
*
* buf1.swap64();
*
* console.log(buf1);
* // Prints: <Buffer 08 07 06 05 04 03 02 01>
*
* const buf2 = Buffer.from([0x1, 0x2, 0x3]);
*
* buf2.swap64();
* // Throws ERR_INVALID_BUFFER_SIZE.
* ```
* @since v6.3.0
* @return A reference to `buf`.
*/
swap64(): Buffer;
/**
* 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.
*
* ```js
* 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: <Buffer 03 04 23 42>
|
* ```
* @since v0.5.0
* @param value Number to be written to `buf`.
* @param [offset=0] Number of bytes to skip before starting to write. Must satisfy `0 <= offset <= buf.length - 1`.
* @return `offset` plus the number of bytes written.
*/
writeUInt8(value: number, offset?: number): number;
/**
* @alias Buffer.writeUInt8
* @since v14.9.0, v12.19.0
*/
writeUint8(value: number, offset?: number): number;
/**
* 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.
*
* ```js
* import { Buffer } from 'node:buffer';
*
* const buf = Buffer.allocUnsafe(4);
*
* buf.writeUInt16LE(0xdead, 0);
* buf.writeUInt16LE(0xbeef, 2);
*
* console.log(buf);
* // Prints: <Buffer ad de ef be>
* ```
* @since v0.5.5
* @param value Number to be written to `buf`.
* @param [offset=0] Number of bytes to skip before starting to write. Must satisfy `0 <= offset <= buf.length - 2`.
* @return `offset` plus the number of bytes written.
*/
writeUInt16LE(value: number, offset?: number): number;
/**
* @alias Buffer.writeUInt16LE
* @since v14.9.0, v12.19.0
*/
writeUint16LE(value: number, offset?: number): number;
/**
* 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.
*
* ```js
* import { Buffer } from 'node:buffer';
*
* const buf = Buffer.allocUnsafe(4);
*
* buf.writeUInt16BE(0xdead, 0);
* buf.writeUInt16BE(0xbeef, 2);
*
* console.log(buf);
* // Prints: <Buffer de ad be ef>
* ```
* @since v0.5.5
* @param value Number to be written to `buf`.
* @param [offset=0] Number of bytes to skip before starting to write. Must satisfy `0 <= offset <= buf.length - 2`.
* @return `offset` plus the number of bytes written.
*/
writeUInt16BE(value: number, offset?: number): number;
/**
* @alias Buffer.writeUInt16BE
* @since v14.9.0, v12.19.0
*/
writeUint16BE(value: number, offset?: number): number;
/**
* 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.
*
* ```js
* import { Buffer } from 'node:buffer';
*
* const buf = Buffer.allocUnsafe(4);
*
* buf.writeUInt32LE(0xfeedface, 0);
*
* console.log(buf);
* // Prints: <Buffer ce fa ed fe>
* ```
* @since v0.5.5
* @param value Number to be written to `buf`.
* @param [offset=0] Number of bytes to skip before starting to write. Must satisfy `0 <= offset <= buf.length - 4`.
* @r |
eturn `offset` plus the number of bytes written.
*/
writeUInt32LE(value: number, offset?: number): number;
/**
* @alias Buffer.writeUInt32LE
* @since v14.9.0, v12.19.0
*/
writeUint32LE(value: number, offset?: number): number;
/**
* 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.
*
* ```js
* import { Buffer } from 'node:buffer';
*
* const buf = Buffer.allocUnsafe(4);
*
* buf.writeUInt32BE(0xfeedface, 0);
*
* console.log(buf);
* // Prints: <Buffer fe ed fa ce>
* ```
* @since v0.5.5
* @param value Number to be written to `buf`.
* @param [offset=0] Number of bytes to skip before starting to write. Must satisfy `0 <= offset <= buf.length - 4`.
* @return `offset` plus the number of bytes written.
*/
writeUInt32BE(value: number, offset?: number): number;
/**
* @alias Buffer.writeUInt32BE
* @since v14.9.0, v12.19.0
*/
writeUint32BE(value: number, offset?: number): number;
/**
* Writes `value` to `buf` at the specified `offset`. `value` must be a valid
* signed 8-bit integer. Behavior is undefined when `value` is anything other than
* a signed 8-bit integer.
*
* `value` is interpreted and written as a two's complement signed integer.
*
* ```js
* import { Buffer } from 'node:buffer';
*
* const buf = Buffer.allocUnsafe(2);
*
* buf.writeInt8(2, 0);
* buf.writeInt8(-2, 1);
*
* console.log(buf);
* // Prints: <Buffer 02 fe>
* ```
* @since v0.5.0
* @param value Number to be written to `buf`.
* @param [offset=0] Number of bytes to skip before starting to write. Must satisfy `0 <= offset <= buf.length - 1`.
* @return `offset` plus the number of bytes written.
*/
writeInt8(value: number, offset?: number): number;
/**
* Writes `value` to `buf` at the specified `offset` as little-endian. The `value`must be a valid signed 16-bit integer. Behavior is undefined when `value` is
* anything other than a signed 16-bit integer.
*
* The `value` is interpreted and written as a two's complement signed integer.
*
* ```js
* import { Buffer } from 'node:buffer';
*
* const buf = Buffer.allocUnsafe(2);
*
* buf.writeInt16LE(0x0304, 0);
*
* console.log(buf);
* // Prints: <Buffer 04 03>
* ```
* @since v0.5.5
* @param value Number to be written to `buf`.
* @param [offset=0] Number of bytes to skip before starting to write. Must satisfy `0 <= offset <= buf.length - 2`.
* @return `offset` plus the number of bytes written.
*/
writeInt16LE(value: number, offset?: number): number;
/**
* Writes `value` to `buf` at the specified `offset` as big-endian. The `value`must be a valid signed 16-bit integer. Behavior is undefined when `value` is
* anything other than a signed 16-bit integer.
*
* The `value` is interpreted and written as a two's complement signed integer.
*
|
* ```js
* import { Buffer } from 'node:buffer';
*
* const buf = Buffer.allocUnsafe(2);
*
* buf.writeInt16BE(0x0102, 0);
*
* console.log(buf);
* // Prints: <Buffer 01 02>
* ```
* @since v0.5.5
* @param value Number to be written to `buf`.
* @param [offset=0] Number of bytes to skip before starting to write. Must satisfy `0 <= offset <= buf.length - 2`.
* @return `offset` plus the number of bytes written.
*/
writeInt16BE(value: number, offset?: number): number;
/**
* 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.
*
* ```js
* import { Buffer } from 'node:buffer';
*
* const buf = Buffer.allocUnsafe(4);
*
* buf.writeInt32LE(0x05060708, 0);
*
* console.log(buf);
* // Prints: <Buffer 08 07 06 05>
* ```
* @since v0.5.5
* @param value Number to be written to `buf`.
* @param [offset=0] Number of bytes to skip before starting to write. Must satisfy `0 <= offset <= buf.length - 4`.
* @return `offset` plus the number of bytes written.
*/
writeInt32LE(value: number, offset?: number): number;
/**
* 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.
*
* ```js
* import { Buffer } from 'node:buffer';
*
* const buf = Buffer.allocUnsafe(4);
*
* buf.writeInt32BE(0x01020304, 0);
*
* console.log(buf);
* // Prints: <Buffer 01 02 03 04>
* ```
* @since v0.5.5
* @param value Number to be written to `buf`.
* @param [offset=0] Number of bytes to skip before starting to write. Must satisfy `0 <= offset <= buf.length - 4`.
* @return `offset` plus the number of bytes written.
*/
writeInt32BE(value: number, offset?: number): number;
/**
* Writes `value` to `buf` at the specified `offset` as little-endian. Behavior is
* undefined when `value` is anything other than a JavaScript number.
*
* ```js
* import { Buffer } from 'node:buffer';
*
* const buf = Buffer.allocUnsafe(4);
*
* buf.writeFloatLE(0xcafebabe, 0);
*
* console.log(buf);
* // Prints: <Buffer bb fe 4a 4f>
* ```
* @since v0.11.15
* @param value Number to be written to `buf`.
* @param [offset=0] Number of bytes to skip before starting to write. Must satisfy `0 <= offset <= buf.length - 4`.
* @return `offset` plus the number of bytes written.
*/
writeFloatLE(value: number, offset?: number): number;
/**
* Writes `value` to `buf` at the specified `offset` as big-endian. Behavior is
* undefined when `value` is anything other than a JavaScript number.
*
* ```js
* import { Buffer } from 'node:buffer';
*
* const buf = Buffer.allocUnsafe(4 |
);
*
* buf.writeFloatBE(0xcafebabe, 0);
*
* console.log(buf);
* // Prints: <Buffer 4f 4a fe bb>
* ```
* @since v0.11.15
* @param value Number to be written to `buf`.
* @param [offset=0] Number of bytes to skip before starting to write. Must satisfy `0 <= offset <= buf.length - 4`.
* @return `offset` plus the number of bytes written.
*/
writeFloatBE(value: number, offset?: number): number;
/**
* Writes `value` to `buf` at the specified `offset` as little-endian. The `value`must be a JavaScript number. Behavior is undefined when `value` is anything
* other than a JavaScript number.
*
* ```js
* import { Buffer } from 'node:buffer';
*
* const buf = Buffer.allocUnsafe(8);
*
* buf.writeDoubleLE(123.456, 0);
*
* console.log(buf);
* // Prints: <Buffer 77 be 9f 1a 2f dd 5e 40>
* ```
* @since v0.11.15
* @param value Number to be written to `buf`.
* @param [offset=0] Number of bytes to skip before starting to write. Must satisfy `0 <= offset <= buf.length - 8`.
* @return `offset` plus the number of bytes written.
*/
writeDoubleLE(value: number, offset?: number): number;
/**
* Writes `value` to `buf` at the specified `offset` as big-endian. The `value`must be a JavaScript number. Behavior is undefined when `value` is anything
* other than a JavaScript number.
*
* ```js
* import { Buffer } from 'node:buffer';
*
* const buf = Buffer.allocUnsafe(8);
*
* buf.writeDoubleBE(123.456, 0);
*
* console.log(buf);
* // Prints: <Buffer 40 5e dd 2f 1a 9f be 77>
* ```
* @since v0.11.15
* @param value Number to be written to `buf`.
* @param [offset=0] Number of bytes to skip before starting to write. Must satisfy `0 <= offset <= buf.length - 8`.
* @return `offset` plus the number of bytes written.
*/
writeDoubleBE(value: number, offset?: number): number;
/**
* Fills `buf` with the specified `value`. If the `offset` and `end` are not given,
* the entire `buf` will be filled:
*
* ```js
* import { Buffer } from 'node:buffer';
*
* // Fill a `Buffer` with the ASCII character 'h'.
*
* const b = Buffer.allocUnsafe(50).fill('h');
*
* console.log(b.toString());
* // Prints: hhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhh
*
* // Fill a buffer with empty string
* const c = Buffer.allocUnsafe(5).fill('');
*
* console.log(c.fill(''));
* // Prints: <Buffer 00 00 00 00 00>
* ```
*
* `value` is coerced to a `uint32` value if it is not a string, `Buffer`, or
* integer. If the resulting integer is greater than `255` (decimal), `buf` will be
* filled with `value & 255`.
*
* If the final write of a `fill()` operation falls on a multi-byte character,
* then only the bytes of that character that fit into `buf` are written:
*
* ```js
* import { Buffer } from 'node:buffer';
*
* // Fill a `Buffer` with character that takes up two bytes in UTF-8.
*
* console.log(Buffer.allocUnsafe(5).fill('\u0222'));
* // Prints: <Buffer c8 a2 c8 a2 c8>
* ```
|
*
* If `value` contains invalid characters, it is truncated; if no valid
* fill data remains, an exception is thrown:
*
* ```js
* import { Buffer } from 'node:buffer';
*
* const buf = Buffer.allocUnsafe(5);
*
* console.log(buf.fill('a'));
* // Prints: <Buffer 61 61 61 61 61>
* console.log(buf.fill('aazz', 'hex'));
* // Prints: <Buffer aa aa aa aa aa>
* console.log(buf.fill('zz', 'hex'));
* // Throws an exception.
* ```
* @since v0.5.0
* @param value The value with which to fill `buf`. Empty value (string, Uint8Array, Buffer) is coerced to `0`.
* @param [offset=0] Number of bytes to skip before starting to fill `buf`.
* @param [end=buf.length] Where to stop filling `buf` (not inclusive).
* @param [encoding='utf8'] The encoding for `value` if `value` is a string.
* @return A reference to `buf`.
*/
fill(value: string | Uint8Array | number, offset?: number, end?: number, encoding?: BufferEncoding): this;
/**
* If `value` is:
*
* * a string, `value` is interpreted according to the character encoding in`encoding`.
* * a `Buffer` or [`Uint8Array`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Uint8Array), `value` will be used in its entirety.
* To compare a partial `Buffer`, use `buf.subarray`.
* * a number, `value` will be interpreted as an unsigned 8-bit integer
* value between `0` and `255`.
*
* ```js
* import { Buffer } from 'node:buffer';
*
* const buf = Buffer.from('this is a buffer');
*
* console.log(buf.indexOf('this'));
* // Prints: 0
* console.log(buf.indexOf('is'));
* // Prints: 2
* console.log(buf.indexOf(Buffer.from('a buffer')));
* // Prints: 8
* console.log(buf.indexOf(97));
* // Prints: 8 (97 is the decimal ASCII value for 'a')
* console.log(buf.indexOf(Buffer.from('a buffer example')));
* // Prints: -1
* console.log(buf.indexOf(Buffer.from('a buffer example').slice(0, 8)));
* // Prints: 8
*
* const utf16Buffer = Buffer.from('\u039a\u0391\u03a3\u03a3\u0395', 'utf16le');
*
* console.log(utf16Buffer.indexOf('\u03a3', 0, 'utf16le'));
* // Prints: 4
* console.log(utf16Buffer.indexOf('\u03a3', -4, 'utf16le'));
* // Prints: 6
* ```
*
* If `value` is not a string, number, or `Buffer`, this method will throw a`TypeError`. If `value` is a number, it will be coerced to a valid byte value,
* an integer between 0 and 255.
*
* If `byteOffset` is not a number, it will be coerced to a number. If the result
* of coercion is `NaN` or `0`, then the entire buffer will be searched. This
* behavior matches [`String.prototype.indexOf()`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/String/indexOf).
*
* ```js
* import { Buffer } from 'node:buffer';
*
* const b = Buffer.from('abcdef');
*
* // Passing a value that's a number, but not a valid byte.
* // Prints: 2, equivalent to searching for 99 or 'c'.
* console.log(b.indexOf(99.9));
* console.log(b.indexOf(256 + 99));
*
* // Passing a byteOffset that coerces to NaN or 0.
* // Prints: 1, searching the whole buffer.
* console.log(b. |
indexOf('b', undefined));
* console.log(b.indexOf('b', {}));
* console.log(b.indexOf('b', null));
* console.log(b.indexOf('b', []));
* ```
*
* If `value` is an empty string or empty `Buffer` and `byteOffset` is less
* than `buf.length`, `byteOffset` will be returned. If `value` is empty and`byteOffset` is at least `buf.length`, `buf.length` will be returned.
* @since v1.5.0
* @param value What to search for.
* @param [byteOffset=0] Where to begin searching in `buf`. If negative, then offset is calculated from the end of `buf`.
* @param [encoding='utf8'] If `value` is a string, this is the encoding used to determine the binary representation of the string that will be searched for in `buf`.
* @return The index of the first occurrence of `value` in `buf`, or `-1` if `buf` does not contain `value`.
*/
indexOf(value: string | number | Uint8Array, byteOffset?: number, encoding?: BufferEncoding): number;
/**
* Identical to `buf.indexOf()`, except the last occurrence of `value` is found
* rather than the first occurrence.
*
* ```js
* import { Buffer } from 'node:buffer';
*
* const buf = Buffer.from('this buffer is a buffer');
*
* console.log(buf.lastIndexOf('this'));
* // Prints: 0
* console.log(buf.lastIndexOf('buffer'));
* // Prints: 17
* console.log(buf.lastIndexOf(Buffer.from('buffer')));
* // Prints: 17
* console.log(buf.lastIndexOf(97));
* // Prints: 15 (97 is the decimal ASCII value for 'a')
* console.log(buf.lastIndexOf(Buffer.from('yolo')));
* // Prints: -1
* console.log(buf.lastIndexOf('buffer', 5));
* // Prints: 5
* console.log(buf.lastIndexOf('buffer', 4));
* // Prints: -1
*
* const utf16Buffer = Buffer.from('\u039a\u0391\u03a3\u03a3\u0395', 'utf16le');
*
* console.log(utf16Buffer.lastIndexOf('\u03a3', undefined, 'utf16le'));
* // Prints: 6
* console.log(utf16Buffer.lastIndexOf('\u03a3', -5, 'utf16le'));
* // Prints: 4
* ```
*
* If `value` is not a string, number, or `Buffer`, this method will throw a`TypeError`. If `value` is a number, it will be coerced to a valid byte value,
* an integer between 0 and 255.
*
* If `byteOffset` is not a number, it will be coerced to a number. Any arguments
* that coerce to `NaN`, like `{}` or `undefined`, will search the whole buffer.
* This behavior matches [`String.prototype.lastIndexOf()`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/String/lastIndexOf).
*
* ```js
* import { Buffer } from 'node:buffer';
*
* const b = Buffer.from('abcdef');
*
* // Passing a value that's a number, but not a valid byte.
* // Prints: 2, equivalent to searching for 99 or 'c'.
* console.log(b.lastIndexOf(99.9));
* console.log(b.lastIndexOf(256 + 99));
*
* // Passing a byteOffset that coerces to NaN.
* // Prints: 1, searching the whole buffer.
* console.log(b.lastIndexOf('b', undefined));
* console.log(b.lastIndexOf('b', {}));
*
* // Passing a byteOffset that coerces to 0.
* // Prints: -1, equivalent to passing 0.
* console.log(b.lastIndexOf('b', null));
* console.log(b.lastIndexOf('b', []));
* ```
*
* If `value` is an |
empty string or empty `Buffer`, `byteOffset` will be returned.
* @since v6.0.0
* @param value What to search for.
* @param [byteOffset=buf.length - 1] Where to begin searching in `buf`. If negative, then offset is calculated from the end of `buf`.
* @param [encoding='utf8'] If `value` is a string, this is the encoding used to determine the binary representation of the string that will be searched for in `buf`.
* @return The index of the last occurrence of `value` in `buf`, or `-1` if `buf` does not contain `value`.
*/
lastIndexOf(value: string | number | Uint8Array, byteOffset?: number, encoding?: BufferEncoding): number;
/**
* Creates and returns an [iterator](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Iteration_protocols) of `[index, byte]` pairs from the contents
* of `buf`.
*
* ```js
* import { Buffer } from 'node:buffer';
*
* // Log the entire contents of a `Buffer`.
*
* const buf = Buffer.from('buffer');
*
* for (const pair of buf.entries()) {
* console.log(pair);
* }
* // Prints:
* // [0, 98]
* // [1, 117]
* // [2, 102]
* // [3, 102]
* // [4, 101]
* // [5, 114]
* ```
* @since v1.1.0
*/
entries(): IterableIterator<[number, number]>;
/**
* Equivalent to `buf.indexOf() !== -1`.
*
* ```js
* import { Buffer } from 'node:buffer';
*
* const buf = Buffer.from('this is a buffer');
*
* console.log(buf.includes('this'));
* // Prints: true
* console.log(buf.includes('is'));
* // Prints: true
* console.log(buf.includes(Buffer.from('a buffer')));
* // Prints: true
* console.log(buf.includes(97));
* // Prints: true (97 is the decimal ASCII value for 'a')
* console.log(buf.includes(Buffer.from('a buffer example')));
* // Prints: false
* console.log(buf.includes(Buffer.from('a buffer example').slice(0, 8)));
* // Prints: true
* console.log(buf.includes('this', 4));
* // Prints: false
* ```
* @since v5.3.0
* @param value What to search for.
* @param [byteOffset=0] Where to begin searching in `buf`. If negative, then offset is calculated from the end of `buf`.
* @param [encoding='utf8'] If `value` is a string, this is its encoding.
* @return `true` if `value` was found in `buf`, `false` otherwise.
*/
includes(value: string | number | Buffer, byteOffset?: number, encoding?: BufferEncoding): boolean;
/**
* Creates and returns an [iterator](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Iteration_protocols) of `buf` keys (indices).
*
* ```js
* import { Buffer } from 'node:buffer';
*
* const buf = Buffer.from('buffer');
*
* for (const key of buf.keys()) {
* console.log(key);
* }
* // Prints:
* // 0
* // 1
* // 2
* // 3
* // 4
* // 5
* ```
* @since v1.1.0
*/
keys(): IterableIterator<number>;
/**
* Creates and returns an [iterator](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Iteration_protocols) for `buf` values (bytes). This function is
* called autom |
atically when a `Buffer` is used in a `for..of` statement.
*
* ```js
* import { Buffer } from 'node:buffer';
*
* const buf = Buffer.from('buffer');
*
* for (const value of buf.values()) {
* console.log(value);
* }
* // Prints:
* // 98
* // 117
* // 102
* // 102
* // 101
* // 114
*
* for (const value of buf) {
* console.log(value);
* }
* // Prints:
* // 98
* // 117
* // 102
* // 102
* // 101
* // 114
* ```
* @since v1.1.0
*/
values(): IterableIterator<number>;
}
var Buffer: BufferConstructor;
/**
* 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')`.**
* @since v15.13.0, v14.17.0
* @legacy Use `Buffer.from(data, 'base64')` instead.
* @param data The Base64-encoded input string.
*/
function atob(data: string): 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')`.**
* @since v15.13.0, v14.17.0
* @legacy Use `buf.toString('base64')` instead.
* @param data An ASCII (Latin1) string.
*/
function btoa(data: string): string;
interface Blob extends __Blob {}
/**
* `Blob` class is a global reference for `require('node:buffer').Blob`
* https://nodejs.org/api/buffer.html#class-blob
* @since v18.0.0
*/
var Blob: typeof globalThis extends {
onmessage: any;
Blob: infer T;
} ? T
: typeof NodeBlob;
}
}
declare module "node:buffer" {
export * from "buffer";
}
|
/**
* The `node:querystring` module provides utilities for parsing and formatting URL
* query strings. It can be accessed using:
*
* ```js
* const querystring = require('node:querystring');
* ```
*
* `querystring` is more performant than `URLSearchParams` but is not a
* standardized API. Use `URLSearchParams` when performance is not critical or
* when compatibility with browser code is desirable.
* @see [source](https://github.com/nodejs/node/blob/v20.2.0/lib/querystring.js)
*/
declare module "querystring" {
interface StringifyOptions {
encodeURIComponent?: ((str: string) => string) | undefined;
}
interface ParseOptions {
maxKeys?: number | undefined;
decodeURIComponent?: ((str: string) => string) | undefined;
}
interface ParsedUrlQuery extends NodeJS.Dict<string | string[]> {}
interface ParsedUrlQueryInput extends
NodeJS.Dict<
| string
| number
| boolean
| readonly string[]
| readonly number[]
| readonly boolean[]
| null
>
{}
/**
* The `querystring.stringify()` method produces a URL query string from a
* given `obj` by iterating through the object's "own properties".
*
* It serializes the following types of values passed in `obj`:[string](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type) |
* [number](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type) |
* [bigint](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/BigInt) |
* [boolean](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Boolean_type) |
* [string\[\]](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type) |
* [number\[\]](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type) |
* [bigint\[\]](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/BigInt) |
* [boolean\[\]](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Boolean_type) The numeric values must be finite. Any other input values will be coerced to
* empty strings.
*
* ```js
* querystring.stringify({ foo: 'bar', baz: ['qux', 'quux'], corge: '' });
* // Returns 'foo=bar&baz=qux&baz=quux&corge='
*
* querystring.stringify({ foo: 'bar', baz: 'qux' }, ';', ':');
* // Returns 'foo:bar;baz:qux'
* ```
*
* By default, characters requiring percent-encoding within the query string will
* be encoded as UTF-8\. If an alternative encoding is required, then an alternative`encodeURIComponent` option will need to be specified:
*
* ```js
* // Assuming gbkEncodeURIComponent function already exists,
*
* querystring.stringify({ w: '中文', foo: 'bar' }, null, null,
* { encodeURIComponent: gbkEncodeURIComponent });
* ```
* @since v0.1.25
* @param obj The object to serialize into a URL query string
* @param [sep='&'] The substring used to delimit key and value pairs in the query string.
* @param [eq='='] . The substring used to delimit keys and values in the query string.
*/
function stringify(obj?: ParsedUrlQueryInput, sep?: string, eq?: string, options?: StringifyOptions): string;
/**
* The `querystring.parse()` method parses a URL query string (`str`) into a
* collection of key and value pairs.
*
* For example, the query string `'foo=bar&abc=xyz&abc=123'` is parsed into:
*
* ```json
* {
* "foo": "bar",
* "abc": ["xyz", "123"]
* }
* ```
*
* The object returned by the `querystring.parse()` method _does not_prototypically inherit from the JavaScript `Object`. This means that typical`Object` methods such as `obj.toString()`,
* `obj.hasOwnPr |
operty()`, and others
* are not defined and _will not work_.
*
* By default, percent-encoded characters within the query string will be assumed
* to use UTF-8 encoding. If an alternative character encoding is used, then an
* alternative `decodeURIComponent` option will need to be specified:
*
* ```js
* // Assuming gbkDecodeURIComponent function already exists...
*
* querystring.parse('w=%D6%D0%CE%C4&foo=bar', null, null,
* { decodeURIComponent: gbkDecodeURIComponent });
* ```
* @since v0.1.25
* @param str The URL query string to parse
* @param [sep='&'] The substring used to delimit key and value pairs in the query string.
* @param [eq='='] . The substring used to delimit keys and values in the query string.
*/
function parse(str: string, sep?: string, eq?: string, options?: ParseOptions): ParsedUrlQuery;
/**
* The querystring.encode() function is an alias for querystring.stringify().
*/
const encode: typeof stringify;
/**
* The querystring.decode() function is an alias for querystring.parse().
*/
const decode: typeof parse;
/**
* The `querystring.escape()` method performs URL percent-encoding on the given`str` in a manner that is optimized for the specific requirements of URL
* query strings.
*
* The `querystring.escape()` method is used by `querystring.stringify()` and is
* generally not expected to be used directly. It is exported primarily to allow
* application code to provide a replacement percent-encoding implementation if
* necessary by assigning `querystring.escape` to an alternative function.
* @since v0.1.25
*/
function escape(str: string): string;
/**
* The `querystring.unescape()` method performs decoding of URL percent-encoded
* characters on the given `str`.
*
* The `querystring.unescape()` method is used by `querystring.parse()` and is
* generally not expected to be used directly. It is exported primarily to allow
* application code to provide a replacement decoding implementation if
* necessary by assigning `querystring.unescape` to an alternative function.
*
* By default, the `querystring.unescape()` method will attempt to use the
* JavaScript built-in `decodeURIComponent()` method to decode. If that fails,
* a safer equivalent that does not throw on malformed URLs will be used.
* @since v0.1.25
*/
function unescape(str: string): string;
}
declare module "node:querystring" {
export * from "querystring";
}
|
/**
* The `node:worker_threads` module enables the use of threads that execute
* JavaScript in parallel. To access it:
*
* ```js
* const worker = require('node:worker_threads');
* ```
*
* Workers (threads) are useful for performing CPU-intensive JavaScript operations.
* They do not help much with I/O-intensive work. The Node.js built-in
* asynchronous I/O operations are more efficient than Workers can be.
*
* Unlike `child_process` or `cluster`, `worker_threads` can share memory. They do
* so by transferring `ArrayBuffer` instances or sharing `SharedArrayBuffer`instances.
*
* ```js
* const {
* Worker, isMainThread, parentPort, workerData,
* } = require('node:worker_threads');
*
* if (isMainThread) {
* module.exports = function parseJSAsync(script) {
* return new Promise((resolve, reject) => {
* const worker = new Worker(__filename, {
* workerData: script,
* });
* worker.on('message', resolve);
* worker.on('error', reject);
* worker.on('exit', (code) => {
* if (code !== 0)
* reject(new Error(`Worker stopped with exit code ${code}`));
* });
* });
* };
* } else {
* const { parse } = require('some-js-parsing-library');
* const script = workerData;
* parentPort.postMessage(parse(script));
* }
* ```
*
* The above example spawns a Worker thread for each `parseJSAsync()` call. In
* practice, use a pool of Workers for these kinds of tasks. Otherwise, the
* overhead of creating Workers would likely exceed their benefit.
*
* When implementing a worker pool, use the `AsyncResource` API to inform
* diagnostic tools (e.g. to provide asynchronous stack traces) about the
* correlation between tasks and their outcomes. See `"Using AsyncResource for a Worker thread pool"` in the `async_hooks` documentation for an example implementation.
*
* Worker threads inherit non-process-specific options by default. Refer to `Worker constructor options` to know how to customize worker thread options,
* specifically `argv` and `execArgv` options.
* @see [source](https://github.com/nodejs/node/blob/v20.2.0/lib/worker_threads.js)
*/
declare module "worker_threads" {
import { Blob } from "node:buffer";
import { Context } from "node:vm";
import { EventEmitter } from "node:events";
import { EventLoopUtilityFunction } from "node:perf_hooks";
import { FileHandle } from "node:fs/promises";
import { Readable, Writable } from "node:stream";
import { URL } from "node:url";
import { X509Certificate } from "node:crypto";
const isMainThread: boolean;
const parentPort: null | MessagePort;
const resourceLimits: ResourceLimits;
const SHARE_ENV: unique symbol;
const threadId: number;
const workerData: any;
/**
* Instances of the `worker.MessageChannel` class represent an asynchronous,
* two-way communications channel.
* The `MessageChannel` has no methods of its own. `new MessageChannel()`yields an object with `port1` and `port2` properties, which refer to linked `MessagePort` instances.
*
* ```js
* const { MessageChannel } = require('node:worker_threads');
*
* const { port1, port2 } = new MessageChannel();
* port1.on('message', (message) => console.log('received', message));
* port2.postMessage({ foo: 'bar' });
* // Prints: received { foo: 'bar' } from the `port1.on('message')` listener
* ```
* @since v10.5.0
*/
class MessageChannel {
readonly port1: MessagePort;
readonly port2: MessagePort;
}
interface WorkerPerformance {
eventLoopUtilization: EventLoopUtilityFunction;
}
type TransferListItem = ArrayBuffer | MessagePort | FileHandle | X509Certificate | Blob;
/**
* Instances of the `worker.MessagePort` class represent one end of an
* asynchronous, two-way communications channel. It can be used to transfer
* structured data, memory regions and other `Mess |