{"$schema":"https://doc-kit.nodejs.org/schemas/api-doc/1.0.0.json","id":"repl","path":"/repl","type":"module","module":"repl","title":"REPL","introducedIn":"v0.10.0","sourceLink":{"path":"lib/repl.js","url":"https://github.com/nodejs/node/blob/HEAD/lib/repl.js"},"stability":{"index":"2","description":"Stable"},"added":[],"deprecated":[],"removed":[],"napiVersion":[],"changes":[],"description":"The `node:repl` module provides a Read-Eval-Print-Loop (REPL) implementation\nthat is available both as a standalone program or includible in other\napplications. It can be accessed using:\n\n```mjs\nimport repl from 'node:repl';\n```\n\n```cjs\nconst repl = require('node:repl');\n```","summary":"The `node:repl` module provides a Read-Eval-Print-Loop (REPL) implementation that is available both as a standalone program or includible in other applications. It can be accessed using:","examples":[{"language":"mjs","displayName":null,"code":"import repl from 'node:repl';"},{"language":"cjs","displayName":null,"code":"const repl = require('node:repl');"}],"children":[{"kind":"section","id":"design-and-features","name":"Design and features","title":"Design and features","scope":"module","overloadOf":null,"stability":null,"added":[],"deprecated":[],"removed":[],"napiVersion":[],"changes":[],"description":"The `node:repl` module exports the [`repl.REPLServer`](#class-replserver) class. While running,\ninstances of [`repl.REPLServer`](#class-replserver) will accept individual lines of user input,\nevaluate those according to a user-defined evaluation function, then output the\nresult. Input and output may be from `stdin` and `stdout`, respectively, or may\nbe connected to any Node.js [stream](stream.html).\n\nInstances of [`repl.REPLServer`](#class-replserver) support automatic completion of inputs,\ncompletion preview, simplistic Emacs-style line editing, multi-line inputs,\n[ZSH](https://en.wikipedia.org/wiki/Z_shell)-like reverse-i-search, [ZSH](https://en.wikipedia.org/wiki/Z_shell)-like substring-based history search,\nANSI-styled output, saving and restoring current REPL session state, error\nrecovery, and customizable evaluation functions. Terminals that do not support\nANSI styles and Emacs-style line editing automatically fall back to a limited\nfeature set.","summary":"The `node:repl` module exports the `repl.REPLServer` class. While running, instances of `repl.REPLServer` will accept individual lines of user input, evaluate those according to a user-defined evaluation function, then output the result. Input and output may be from `stdin` and `stdout`, respectively, or may be connected to any Node.js stream.","examples":[],"children":[{"kind":"section","id":"commands-and-special-keys","name":"Commands and special keys","title":"Commands and special keys","scope":"module","overloadOf":null,"stability":null,"added":[],"deprecated":[],"removed":[],"napiVersion":[],"changes":[],"description":"The following special commands are supported by all REPL instances:\n\n* `.break`: When in the process of inputting a multi-line expression, enter\n  the `.break` command (or press <kbd>Ctrl</kbd>+<kbd>C</kbd>) to abort\n  further input or processing of that expression.\n* `.clear`: Resets the REPL `context` to an empty object and clears any\n  multi-line expression being input.\n* `.exit`: Close the I/O stream, causing the REPL to exit.\n* `.help`: Show this list of special commands.\n* `.save`: Save the current REPL session to a file:\n  `> .save ./file/to/save.js`\n* `.load`: Load a file into the current REPL session.\n  `> .load ./file/to/load.js`\n* `.editor`: Enter editor mode (<kbd>Ctrl</kbd>+<kbd>D</kbd> to\n  finish, <kbd>Ctrl</kbd>+<kbd>C</kbd> to cancel).\n\n```console\n> .editor\n// Entering editor mode (^D to finish, ^C to cancel)\nfunction welcome(name) {\n  return `Hello ${name}!`;\n}\n\nwelcome('Node.js User');\n\n// ^D\n'Hello Node.js User!'\n>\n```\n\nThe following key combinations in the REPL have these special effects:\n\n* <kbd>Ctrl</kbd>+<kbd>C</kbd>: When pressed once, has the same effect as the\n  `.break` command.\n  When pressed twice on a blank line, has the same effect as the `.exit`\n  command.\n* <kbd>Ctrl</kbd>+<kbd>D</kbd>: Has the same effect as the `.exit` command.\n* <kbd>Tab</kbd>: When pressed on a blank line, displays global and local\n  (scope) variables. When pressed while entering other input, displays relevant\n  autocompletion options.\n\nFor key bindings related to the reverse-i-search, see [`reverse-i-search`](#reverse-i-search).\nFor all other key bindings, see [TTY keybindings](readline.html#tty-keybindings).","summary":"The following special commands are supported by all REPL instances:","examples":[{"language":"console","displayName":null,"code":"> .editor\n// Entering editor mode (^D to finish, ^C to cancel)\nfunction welcome(name) {\n  return `Hello ${name}!`;\n}\n\nwelcome('Node.js User');\n\n// ^D\n'Hello Node.js User!'\n>"}],"children":[]},{"kind":"section","id":"default-evaluation","name":"Default evaluation","title":"Default evaluation","scope":"module","overloadOf":null,"stability":null,"added":[],"deprecated":[],"removed":[],"napiVersion":[],"changes":[],"description":"By default, all instances of [`repl.REPLServer`](#class-replserver) use an evaluation function\nthat evaluates JavaScript expressions and provides access to Node.js built-in\nmodules. This default behavior can be overridden by passing in an alternative\nevaluation function when the [`repl.REPLServer`](#class-replserver) instance is created.","summary":"By default, all instances of `repl.REPLServer` use an evaluation function that evaluates JavaScript expressions and provides access to Node.js built-in modules. This default behavior can be overridden by passing in an alternative evaluation function when the `repl.REPLServer` instance is created.","examples":[],"children":[{"kind":"section","id":"javascript-expressions","name":"JavaScript expressions","title":"JavaScript expressions","scope":"module","overloadOf":null,"stability":null,"added":[],"deprecated":[],"removed":[],"napiVersion":[],"changes":[],"description":"The default evaluator supports direct evaluation of JavaScript expressions:\n\n```console\n> 1 + 1\n2\n> const m = 2\nundefined\n> m + 1\n3\n```\n\nUnless otherwise scoped within blocks or functions, variables declared\neither implicitly or using the `const`, `let`, or `var` keywords\nare declared at the global scope.","summary":"The default evaluator supports direct evaluation of JavaScript expressions:","examples":[{"language":"console","displayName":null,"code":"> 1 + 1\n2\n> const m = 2\nundefined\n> m + 1\n3"}],"children":[]},{"kind":"section","id":"global-and-local-scope","name":"Global and local scope","title":"Global and local scope","scope":"module","overloadOf":null,"stability":null,"added":[],"deprecated":[],"removed":[],"napiVersion":[],"changes":[],"description":"The default evaluator provides access to any variables that exist in the global\nscope. It is possible to expose a variable to the REPL explicitly by assigning\nit to the `context` object associated with each `REPLServer`:\n\n```mjs\nimport repl from 'node:repl';\nconst msg = 'message';\n\nrepl.start('> ').context.m = msg;\n```\n\n```cjs\nconst repl = require('node:repl');\nconst msg = 'message';\n\nrepl.start('> ').context.m = msg;\n```\n\nProperties in the `context` object appear as local within the REPL:\n\n```console\n$ node repl_test.js\n> m\n'message'\n```\n\nContext properties are not read-only by default. To specify read-only globals,\ncontext properties must be defined using `Object.defineProperty()`:\n\n```mjs\nimport repl from 'node:repl';\nconst msg = 'message';\n\nconst r = repl.start('> ');\nObject.defineProperty(r.context, 'm', {\n  configurable: false,\n  enumerable: true,\n  value: msg,\n});\n```\n\n```cjs\nconst repl = require('node:repl');\nconst msg = 'message';\n\nconst r = repl.start('> ');\nObject.defineProperty(r.context, 'm', {\n  configurable: false,\n  enumerable: true,\n  value: msg,\n});\n```","summary":"The default evaluator provides access to any variables that exist in the global scope. It is possible to expose a variable to the REPL explicitly by assigning it to the `context` object associated with each `REPLServer`:","examples":[{"language":"mjs","displayName":null,"code":"import repl from 'node:repl';\nconst msg = 'message';\n\nrepl.start('> ').context.m = msg;"},{"language":"cjs","displayName":null,"code":"const repl = require('node:repl');\nconst msg = 'message';\n\nrepl.start('> ').context.m = msg;"},{"language":"console","displayName":null,"code":"$ node repl_test.js\n> m\n'message'"},{"language":"mjs","displayName":null,"code":"import repl from 'node:repl';\nconst msg = 'message';\n\nconst r = repl.start('> ');\nObject.defineProperty(r.context, 'm', {\n  configurable: false,\n  enumerable: true,\n  value: msg,\n});"},{"language":"cjs","displayName":null,"code":"const repl = require('node:repl');\nconst msg = 'message';\n\nconst r = repl.start('> ');\nObject.defineProperty(r.context, 'm', {\n  configurable: false,\n  enumerable: true,\n  value: msg,\n});"}],"children":[]},{"kind":"section","id":"accessing-core-nodejs-modules","name":"Accessing core Node.js modules","title":"Accessing core Node.js modules","scope":"module","overloadOf":null,"stability":null,"added":[],"deprecated":[],"removed":[],"napiVersion":[],"changes":[],"description":"The default evaluator will automatically load Node.js core modules into the\nREPL environment when used. For instance, unless otherwise declared as a\nglobal or scoped variable, the input `fs` will be evaluated on-demand as\n`global.fs = require('node:fs')`.\n\n```console\n> fs.createReadStream('./some/file');\n```","summary":"The default evaluator will automatically load Node.js core modules into the REPL environment when used. For instance, unless otherwise declared as a global or scoped variable, the input `fs` will be evaluated on-demand as `global.fs = require('node:fs')`.","examples":[{"language":"console","displayName":null,"code":"> fs.createReadStream('./some/file');"}],"children":[]},{"kind":"section","id":"global-uncaught-exceptions","name":"Global uncaught exceptions","title":"Global uncaught exceptions","scope":"module","overloadOf":null,"stability":null,"added":[],"deprecated":[],"removed":[],"napiVersion":[],"changes":[{"versions":["v12.3.0"],"prUrl":"https://github.com/nodejs/node/pull/27151","commit":null,"description":"The `'uncaughtException'` event is from now on triggered if the repl is used as standalone program."}],"description":"The REPL uses the [`domain`](domain.html) module to catch all uncaught exceptions for that\nREPL session.\n\nThis use of the [`domain`](domain.html) module in the REPL has these side effects:\n\n* Uncaught exceptions only emit the [`'uncaughtException'`](process.html#event-uncaughtexception) event in the\n  standalone REPL. Adding a listener for this event in a REPL within\n  another Node.js program results in [`ERR_INVALID_REPL_INPUT`](errors.html#err_invalid_repl_input).\n\n  ```js\n  const r = repl.start();\n\n  r.write('process.on(\"uncaughtException\", () => console.log(\"Foobar\"));\\n');\n  // Output stream includes:\n  //   TypeError [ERR_INVALID_REPL_INPUT]: Listeners for `uncaughtException`\n  //   cannot be used in the REPL\n\n  r.close();\n  ```\n\n* Trying to use [`process.setUncaughtExceptionCaptureCallback()`](process.html#processsetuncaughtexceptioncapturecallbackfn) throws\n  an [`ERR_DOMAIN_CANNOT_SET_UNCAUGHT_EXCEPTION_CAPTURE`](errors.html#err_domain_cannot_set_uncaught_exception_capture) error.","summary":"The REPL uses the `domain` module to catch all uncaught exceptions for that REPL session.","examples":[{"language":"js","displayName":null,"code":"const r = repl.start();\n\nr.write('process.on(\"uncaughtException\", () => console.log(\"Foobar\"));\\n');\n// Output stream includes:\n//   TypeError [ERR_INVALID_REPL_INPUT]: Listeners for `uncaughtException`\n//   cannot be used in the REPL\n\nr.close();"}],"children":[]},{"kind":"section","id":"assignment-of-the-_-underscore-variable","name":"Assignment of the _ (underscore) variable","title":"Assignment of the `_` (underscore) variable","scope":"module","overloadOf":null,"stability":null,"added":[],"deprecated":[],"removed":[],"napiVersion":[],"changes":[{"versions":["v9.8.0"],"prUrl":"https://github.com/nodejs/node/pull/18919","commit":null,"description":"Added `_error` support."}],"description":"The default evaluator will, by default, assign the result of the most recently\nevaluated expression to the special variable `_` (underscore).\nExplicitly setting `_` to a value will disable this behavior.\n\n```console\n> [ 'a', 'b', 'c' ]\n[ 'a', 'b', 'c' ]\n> _.length\n3\n> _ += 1\nExpression assignment to _ now disabled.\n4\n> 1 + 1\n2\n> _\n4\n```\n\nSimilarly, `_error` will refer to the last seen error, if there was any.\nExplicitly setting `_error` to a value will disable this behavior.\n\n```console\n> throw new Error('foo');\nUncaught Error: foo\n> _error.message\n'foo'\n```","summary":"The default evaluator will, by default, assign the result of the most recently evaluated expression to the special variable `_` (underscore). Explicitly setting `_` to a value will disable this behavior.","examples":[{"language":"console","displayName":null,"code":"> [ 'a', 'b', 'c' ]\n[ 'a', 'b', 'c' ]\n> _.length\n3\n> _ += 1\nExpression assignment to _ now disabled.\n4\n> 1 + 1\n2\n> _\n4"},{"language":"console","displayName":null,"code":"> throw new Error('foo');\nUncaught Error: foo\n> _error.message\n'foo'"}],"children":[]},{"kind":"section","id":"await-keyword","name":"await keyword","title":"`await` keyword","scope":"module","overloadOf":null,"stability":null,"added":[],"deprecated":[],"removed":[],"napiVersion":[],"changes":[],"description":"Support for the `await` keyword is enabled at the top level.\n\n```console\n> await Promise.resolve(123)\n123\n> await Promise.reject(new Error('REPL await'))\nUncaught Error: REPL await\n    at REPL2:1:54\n> const timeout = util.promisify(setTimeout);\nundefined\n> const old = Date.now(); await timeout(1000); console.log(Date.now() - old);\n1002\nundefined\n```\n\nOne known limitation of using the `await` keyword in the REPL is that\nit will invalidate the lexical scoping of the `const` keywords.\n\nFor example:\n\n```console\n> const m = await Promise.resolve(123)\nundefined\n> m\n123\n> m = await Promise.resolve(234)\n234\n// redeclaring the constant does error\n> const m = await Promise.resolve(345)\nUncaught SyntaxError: Identifier 'm' has already been declared\n```\n\n[`--no-experimental-repl-await`](cli.html#--no-experimental-repl-await) shall disable top-level await in REPL.","summary":"Support for the `await` keyword is enabled at the top level.","examples":[{"language":"console","displayName":null,"code":"> await Promise.resolve(123)\n123\n> await Promise.reject(new Error('REPL await'))\nUncaught Error: REPL await\n    at REPL2:1:54\n> const timeout = util.promisify(setTimeout);\nundefined\n> const old = Date.now(); await timeout(1000); console.log(Date.now() - old);\n1002\nundefined"},{"language":"console","displayName":null,"code":"> const m = await Promise.resolve(123)\nundefined\n> m\n123\n> m = await Promise.resolve(234)\n234\n// redeclaring the constant does error\n> const m = await Promise.resolve(345)\nUncaught SyntaxError: Identifier 'm' has already been declared"}],"children":[]}]},{"kind":"section","id":"reverse-i-search","name":"Reverse-i-search","title":"Reverse-i-search","scope":"module","overloadOf":null,"stability":null,"added":["v13.6.0","v12.17.0"],"deprecated":[],"removed":[],"napiVersion":[],"changes":[],"description":"The REPL supports bi-directional reverse-i-search similar to [ZSH](https://en.wikipedia.org/wiki/Z_shell). It is\ntriggered with <kbd>Ctrl</kbd>+<kbd>R</kbd> to search backward\nand <kbd>Ctrl</kbd>+<kbd>S</kbd> to search forwards.\n\nDuplicated history entries will be skipped.\n\nEntries are accepted as soon as any key is pressed that doesn't correspond\nwith the reverse search. Cancelling is possible by pressing <kbd>Esc</kbd>\nor <kbd>Ctrl</kbd>+<kbd>C</kbd>.\n\nChanging the direction immediately searches for the next entry in the expected\ndirection from the current position on.","summary":"The REPL supports bi-directional reverse-i-search similar to ZSH. It is triggered with <kbd>Ctrl</kbd>+<kbd>R</kbd> to search backward and <kbd>Ctrl</kbd>+<kbd>S</kbd> to search forwards.","examples":[],"children":[]},{"kind":"section","id":"custom-evaluation-functions","name":"Custom evaluation functions","title":"Custom evaluation functions","scope":"module","overloadOf":null,"stability":null,"added":[],"deprecated":[],"removed":[],"napiVersion":[],"changes":[],"description":"When a new [`repl.REPLServer`](#class-replserver) is created, a custom evaluation function may be\nprovided. This can be used, for instance, to implement fully customized REPL\napplications.\n\nAn evaluation function accepts the following four arguments:\n\n* `code` {string} The code to be executed (e.g. `1 + 1`).\n* `context` {Object} The context in which the code is executed. This can either be the JavaScript `global`\n  context or a context specific to the REPL instance, depending on the `useGlobal` option.\n* `replResourceName` {string} An identifier for the REPL resource associated with the current code\n  evaluation. This can be useful for debugging purposes.\n* `callback` {Function} A function to invoke once the code evaluation is complete. The callback takes two parameters:\n  * An error object to provide if an error occurred during evaluation, or `null`/`undefined` if no error occurred.\n  * The result of the code evaluation (this is not relevant if an error is provided).\n\nThe following illustrates an example of a REPL that squares a given number, an error is instead printed\nif the provided input is not actually a number:\n\n```mjs\nimport repl from 'node:repl';\n\nfunction byThePowerOfTwo(number) {\n  return number * number;\n}\n\nfunction myEval(code, context, replResourceName, callback) {\n  if (isNaN(code)) {\n    callback(new Error(`${code.trim()} is not a number`));\n  } else {\n    callback(null, byThePowerOfTwo(code));\n  }\n}\n\nrepl.start({ prompt: 'Enter a number: ', eval: myEval });\n```\n\n```cjs\nconst repl = require('node:repl');\n\nfunction byThePowerOfTwo(number) {\n  return number * number;\n}\n\nfunction myEval(code, context, replResourceName, callback) {\n  if (isNaN(code)) {\n    callback(new Error(`${code.trim()} is not a number`));\n  } else {\n    callback(null, byThePowerOfTwo(code));\n  }\n}\n\nrepl.start({ prompt: 'Enter a number: ', eval: myEval });\n```","summary":"When a new `repl.REPLServer` is created, a custom evaluation function may be provided. This can be used, for instance, to implement fully customized REPL applications.","examples":[{"language":"mjs","displayName":null,"code":"import repl from 'node:repl';\n\nfunction byThePowerOfTwo(number) {\n  return number * number;\n}\n\nfunction myEval(code, context, replResourceName, callback) {\n  if (isNaN(code)) {\n    callback(new Error(`${code.trim()} is not a number`));\n  } else {\n    callback(null, byThePowerOfTwo(code));\n  }\n}\n\nrepl.start({ prompt: 'Enter a number: ', eval: myEval });"},{"language":"cjs","displayName":null,"code":"const repl = require('node:repl');\n\nfunction byThePowerOfTwo(number) {\n  return number * number;\n}\n\nfunction myEval(code, context, replResourceName, callback) {\n  if (isNaN(code)) {\n    callback(new Error(`${code.trim()} is not a number`));\n  } else {\n    callback(null, byThePowerOfTwo(code));\n  }\n}\n\nrepl.start({ prompt: 'Enter a number: ', eval: myEval });"}],"children":[{"kind":"section","id":"recoverable-errors","name":"Recoverable errors","title":"Recoverable errors","scope":"module","overloadOf":null,"stability":null,"added":[],"deprecated":[],"removed":[],"napiVersion":[],"changes":[],"description":"At the REPL prompt, pressing <kbd>Enter</kbd> sends the current line of input to\nthe `eval` function. In order to support multi-line input, the `eval` function\ncan return an instance of `repl.Recoverable` to the provided callback function:\n\n```js\nfunction myEval(cmd, context, filename, callback) {\n  let result;\n  try {\n    result = vm.runInThisContext(cmd);\n  } catch (e) {\n    if (isRecoverableError(e)) {\n      return callback(new repl.Recoverable(e));\n    }\n  }\n  callback(null, result);\n}\n\nfunction isRecoverableError(error) {\n  if (error.name === 'SyntaxError') {\n    return /^(Unexpected end of input|Unexpected token)/.test(error.message);\n  }\n  return false;\n}\n```","summary":"At the REPL prompt, pressing <kbd>Enter</kbd> sends the current line of input to the `eval` function. In order to support multi-line input, the `eval` function can return an instance of `repl.Recoverable` to the provided callback function:","examples":[{"language":"js","displayName":null,"code":"function myEval(cmd, context, filename, callback) {\n  let result;\n  try {\n    result = vm.runInThisContext(cmd);\n  } catch (e) {\n    if (isRecoverableError(e)) {\n      return callback(new repl.Recoverable(e));\n    }\n  }\n  callback(null, result);\n}\n\nfunction isRecoverableError(error) {\n  if (error.name === 'SyntaxError') {\n    return /^(Unexpected end of input|Unexpected token)/.test(error.message);\n  }\n  return false;\n}"}],"children":[]}]},{"kind":"section","id":"customizing-repl-output","name":"Customizing REPL output","title":"Customizing REPL output","scope":"module","overloadOf":null,"stability":null,"added":[],"deprecated":[],"removed":[],"napiVersion":[],"changes":[],"description":"By default, [`repl.REPLServer`](#class-replserver) instances format output using the\n[`util.inspect()`](util.html#utilinspectobject-options) method before writing the output to the provided `Writable`\nstream (`process.stdout` by default). The `showProxy` inspection option is set\nto true by default and the `colors` option is set to true depending on the\nREPL's `useColors` option.\n\nThe `useColors` boolean option can be specified at construction to instruct the\ndefault writer to use ANSI style codes to colorize the output from the\n`util.inspect()` method.\n\nIf the REPL is run as standalone program, it is also possible to change the\nREPL's [inspection defaults](util.html#utilinspectobject-options) from inside the REPL by using the\n`inspect.replDefaults` property which mirrors the `defaultOptions` from\n[`util.inspect()`](util.html#utilinspectobject-options).\n\n```console\n> util.inspect.replDefaults.compact = false;\nfalse\n> [1]\n[\n  1\n]\n>\n```\n\nTo fully customize the output of a [`repl.REPLServer`](#class-replserver) instance pass in a new\nfunction for the `writer` option on construction. The following example, for\ninstance, simply converts any input text to upper case:\n\n```mjs\nimport repl from 'node:repl';\n\nconst r = repl.start({ prompt: '> ', eval: myEval, writer: myWriter });\n\nfunction myEval(cmd, context, filename, callback) {\n  callback(null, cmd);\n}\n\nfunction myWriter(output) {\n  return output.toUpperCase();\n}\n```\n\n```cjs\nconst repl = require('node:repl');\n\nconst r = repl.start({ prompt: '> ', eval: myEval, writer: myWriter });\n\nfunction myEval(cmd, context, filename, callback) {\n  callback(null, cmd);\n}\n\nfunction myWriter(output) {\n  return output.toUpperCase();\n}\n```","summary":"By default, `repl.REPLServer` instances format output using the `util.inspect()` method before writing the output to the provided `Writable` stream (`process.stdout` by default). The `showProxy` inspection option is set to true by default and the `colors` option is set to true depending on the REPL's `useColors` option.","examples":[{"language":"console","displayName":null,"code":"> util.inspect.replDefaults.compact = false;\nfalse\n> [1]\n[\n  1\n]\n>"},{"language":"mjs","displayName":null,"code":"import repl from 'node:repl';\n\nconst r = repl.start({ prompt: '> ', eval: myEval, writer: myWriter });\n\nfunction myEval(cmd, context, filename, callback) {\n  callback(null, cmd);\n}\n\nfunction myWriter(output) {\n  return output.toUpperCase();\n}"},{"language":"cjs","displayName":null,"code":"const repl = require('node:repl');\n\nconst r = repl.start({ prompt: '> ', eval: myEval, writer: myWriter });\n\nfunction myEval(cmd, context, filename, callback) {\n  callback(null, cmd);\n}\n\nfunction myWriter(output) {\n  return output.toUpperCase();\n}"}],"children":[]}]},{"kind":"class","id":"class-replserver","name":"REPLServer","title":"Class: `REPLServer`","scope":"module","overloadOf":null,"stability":null,"added":["v0.1.91"],"deprecated":[],"removed":[],"napiVersion":[],"changes":[],"extends":{"text":"readline.Interface","links":[{"name":"readline.Interface","href":"readline.html#class-readlineinterface","start":0,"end":18}]},"description":"Instances of `repl.REPLServer` are created using the [`repl.start()`](#replstartoptions) method\nor directly using the JavaScript `new` keyword.\n\n```mjs\nimport repl from 'node:repl';\n\nconst options = { useColors: true };\n\nconst firstInstance = repl.start(options);\nconst secondInstance = new repl.REPLServer(options);\n```\n\n```cjs\nconst repl = require('node:repl');\n\nconst options = { useColors: true };\n\nconst firstInstance = repl.start(options);\nconst secondInstance = new repl.REPLServer(options);\n```","summary":"Instances of `repl.REPLServer` are created using the `repl.start()` method or directly using the JavaScript `new` keyword.","examples":[{"language":"mjs","displayName":null,"code":"import repl from 'node:repl';\n\nconst options = { useColors: true };\n\nconst firstInstance = repl.start(options);\nconst secondInstance = new repl.REPLServer(options);"},{"language":"cjs","displayName":null,"code":"const repl = require('node:repl');\n\nconst options = { useColors: true };\n\nconst firstInstance = repl.start(options);\nconst secondInstance = new repl.REPLServer(options);"}],"children":[{"kind":"event","id":"event-exit","name":"exit","title":"Event: `'exit'`","scope":"module","overloadOf":null,"stability":null,"added":["v0.7.7"],"deprecated":[],"removed":[],"napiVersion":[],"changes":[],"parameters":[],"description":"The `'exit'` event is emitted when the REPL is exited either by receiving the\n`.exit` command as input, the user pressing <kbd>Ctrl</kbd>+<kbd>C</kbd> twice\nto signal `SIGINT`,\nor by pressing <kbd>Ctrl</kbd>+<kbd>D</kbd> to signal `'end'` on the input\nstream. The listener\ncallback is invoked without any arguments.\n\n```js\nreplServer.on('exit', () => {\n  console.log('Received \"exit\" event from repl!');\n  process.exit();\n});\n```","summary":"The `'exit'` event is emitted when the REPL is exited either by receiving the `.exit` command as input, the user pressing <kbd>Ctrl</kbd>+<kbd>C</kbd> twice to signal `SIGINT`, or by pressing <kbd>Ctrl</kbd>+<kbd>D</kbd> to signal `'end'` on the input stream. The listener callback is invoked without any arguments.","examples":[{"language":"js","displayName":null,"code":"replServer.on('exit', () => {\n  console.log('Received \"exit\" event from repl!');\n  process.exit();\n});"}],"children":[]},{"kind":"event","id":"event-reset","name":"reset","title":"Event: `'reset'`","scope":"module","overloadOf":null,"stability":null,"added":["v0.11.0"],"deprecated":[],"removed":[],"napiVersion":[],"changes":[],"parameters":[],"description":"The `'reset'` event is emitted when the REPL's context is reset. This occurs\nwhenever the `.clear` command is received as input *unless* the REPL is using\nthe default evaluator and the `repl.REPLServer` instance was created with the\n`useGlobal` option set to `true`. The listener callback will be called with a\nreference to the `context` object as the only argument.\n\nThis can be used primarily to re-initialize REPL context to some pre-defined\nstate:\n\n```mjs\nimport repl from 'node:repl';\n\nfunction initializeContext(context) {\n  context.m = 'test';\n}\n\nconst r = repl.start({ prompt: '> ' });\ninitializeContext(r.context);\n\nr.on('reset', initializeContext);\n```\n\n```cjs\nconst repl = require('node:repl');\n\nfunction initializeContext(context) {\n  context.m = 'test';\n}\n\nconst r = repl.start({ prompt: '> ' });\ninitializeContext(r.context);\n\nr.on('reset', initializeContext);\n```\n\nWhen this code is executed, the global `'m'` variable can be modified but then\nreset to its initial value using the `.clear` command:\n\n```console\n$ ./node example.js\n> m\n'test'\n> m = 1\n1\n> m\n1\n> .clear\nClearing context...\n> m\n'test'\n>\n```","summary":"The `'reset'` event is emitted when the REPL's context is reset. This occurs whenever the `.clear` command is received as input _unless_ the REPL is using the default evaluator and the `repl.REPLServer` instance was created with the `useGlobal` option set to `true`. The listener callback will be called with a reference to the `context` object as the only argument.","examples":[{"language":"mjs","displayName":null,"code":"import repl from 'node:repl';\n\nfunction initializeContext(context) {\n  context.m = 'test';\n}\n\nconst r = repl.start({ prompt: '> ' });\ninitializeContext(r.context);\n\nr.on('reset', initializeContext);"},{"language":"cjs","displayName":null,"code":"const repl = require('node:repl');\n\nfunction initializeContext(context) {\n  context.m = 'test';\n}\n\nconst r = repl.start({ prompt: '> ' });\ninitializeContext(r.context);\n\nr.on('reset', initializeContext);"},{"language":"console","displayName":null,"code":"$ ./node example.js\n> m\n'test'\n> m = 1\n1\n> m\n1\n> .clear\nClearing context...\n> m\n'test'\n>"}],"children":[]},{"kind":"method","id":"replserverdefinecommandkeyword-cmd","name":"defineCommand","title":"`replServer.defineCommand(keyword, cmd)`","scope":"module","overloadOf":null,"stability":null,"added":["v0.3.0"],"deprecated":[],"removed":[],"napiVersion":[],"changes":[],"signature":{"parameters":[{"name":"keyword","type":{"text":"string","links":[{"name":"string","href":"https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#string_type","start":0,"end":6}]},"description":"The command keyword (*without* a leading `.` character).","default":null,"optional":false,"rest":false,"properties":[]},{"name":"cmd","type":{"text":"Object | Function","links":[{"name":"Object","href":"https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Object","start":0,"end":6},{"name":"Function","href":"https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Function","start":9,"end":17}]},"description":"The function to invoke when the command is processed.","default":null,"optional":false,"rest":false,"properties":[]}],"returns":null},"description":"The `replServer.defineCommand()` method is used to add new `.`-prefixed commands\nto the REPL instance. Such commands are invoked by typing a `.` followed by the\n`keyword`. The `cmd` is either a `Function` or an `Object` with the following\nproperties:\n\n* `help` {string} Help text to be displayed when `.help` is entered (Optional).\n* `action` {Function} The function to execute, optionally accepting a single\n  string argument.\n\nThe following example shows two new commands added to the REPL instance:\n\n```mjs\nimport repl from 'node:repl';\n\nconst replServer = repl.start({ prompt: '> ' });\nreplServer.defineCommand('sayhello', {\n  help: 'Say hello',\n  action(name) {\n    this.clearBufferedCommand();\n    console.log(`Hello, ${name}!`);\n    this.displayPrompt();\n  },\n});\nreplServer.defineCommand('saybye', function saybye() {\n  console.log('Goodbye!');\n  this.close();\n});\n```\n\n```cjs\nconst repl = require('node:repl');\n\nconst replServer = repl.start({ prompt: '> ' });\nreplServer.defineCommand('sayhello', {\n  help: 'Say hello',\n  action(name) {\n    this.clearBufferedCommand();\n    console.log(`Hello, ${name}!`);\n    this.displayPrompt();\n  },\n});\nreplServer.defineCommand('saybye', function saybye() {\n  console.log('Goodbye!');\n  this.close();\n});\n```\n\nThe new commands can then be used from within the REPL instance:\n\n```console\n> .sayhello Node.js User\nHello, Node.js User!\n> .saybye\nGoodbye!\n```","summary":"The `replServer.defineCommand()` method is used to add new `.`-prefixed commands to the REPL instance. Such commands are invoked by typing a `.` followed by the `keyword`. The `cmd` is either a `Function` or an `Object` with the following properties:","examples":[{"language":"mjs","displayName":null,"code":"import repl from 'node:repl';\n\nconst replServer = repl.start({ prompt: '> ' });\nreplServer.defineCommand('sayhello', {\n  help: 'Say hello',\n  action(name) {\n    this.clearBufferedCommand();\n    console.log(`Hello, ${name}!`);\n    this.displayPrompt();\n  },\n});\nreplServer.defineCommand('saybye', function saybye() {\n  console.log('Goodbye!');\n  this.close();\n});"},{"language":"cjs","displayName":null,"code":"const repl = require('node:repl');\n\nconst replServer = repl.start({ prompt: '> ' });\nreplServer.defineCommand('sayhello', {\n  help: 'Say hello',\n  action(name) {\n    this.clearBufferedCommand();\n    console.log(`Hello, ${name}!`);\n    this.displayPrompt();\n  },\n});\nreplServer.defineCommand('saybye', function saybye() {\n  console.log('Goodbye!');\n  this.close();\n});"},{"language":"console","displayName":null,"code":"> .sayhello Node.js User\nHello, Node.js User!\n> .saybye\nGoodbye!"}],"children":[]},{"kind":"method","id":"replserverdisplaypromptpreservecursor","name":"displayPrompt","title":"`replServer.displayPrompt([preserveCursor])`","scope":"module","overloadOf":null,"stability":null,"added":["v0.1.91"],"deprecated":[],"removed":[],"napiVersion":[],"changes":[],"signature":{"parameters":[{"name":"preserveCursor","type":{"text":"boolean","links":[{"name":"boolean","href":"https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#boolean_type","start":0,"end":7}]},"description":"","default":null,"optional":true,"rest":false,"properties":[]}],"returns":null},"description":"The `replServer.displayPrompt()` method readies the REPL instance for input\nfrom the user, printing the configured `prompt` to a new line in the `output`\nand resuming the `input` to accept new input.\n\nWhen multi-line input is being entered, a pipe `'|'` is printed rather than the\n'prompt'.\n\nWhen `preserveCursor` is `true`, the cursor placement will not be reset to `0`.\n\nThe `replServer.displayPrompt` method is primarily intended to be called from\nwithin the action function for commands registered using the\n`replServer.defineCommand()` method.","summary":"The `replServer.displayPrompt()` method readies the REPL instance for input from the user, printing the configured `prompt` to a new line in the `output` and resuming the `input` to accept new input.","examples":[],"children":[]},{"kind":"method","id":"replserverclearbufferedcommand","name":"clearBufferedCommand","title":"`replServer.clearBufferedCommand()`","scope":"module","overloadOf":null,"stability":null,"added":["v9.0.0"],"deprecated":[],"removed":[],"napiVersion":[],"changes":[],"signature":{"parameters":[],"returns":null},"description":"The `replServer.clearBufferedCommand()` method clears any command that has been\nbuffered but not yet executed. This method is primarily intended to be\ncalled from within the action function for commands registered using the\n`replServer.defineCommand()` method.","summary":"The `replServer.clearBufferedCommand()` method clears any command that has been buffered but not yet executed. This method is primarily intended to be called from within the action function for commands registered using the `replServer.defineCommand()` method.","examples":[],"children":[]},{"kind":"method","id":"replserversetuphistoryhistoryconfig-callback","name":"setupHistory","title":"`replServer.setupHistory(historyConfig, callback)`","scope":"module","overloadOf":null,"stability":null,"added":["v11.10.0"],"deprecated":[],"removed":[],"napiVersion":[],"changes":[{"versions":["v24.2.0"],"prUrl":"https://github.com/nodejs/node/pull/58225","commit":null,"description":"Updated the `historyConfig` parameter to accept an object with `filePath`, `size`, `removeHistoryDuplicates` and `onHistoryFileLoaded` properties."}],"signature":{"parameters":[{"name":"historyConfig","type":{"text":"Object | string","links":[{"name":"Object","href":"https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Object","start":0,"end":6},{"name":"string","href":"https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#string_type","start":9,"end":15}]},"description":"the path to the history file\nIf it is a string, it is the path to the history file.\nIf it is an object, it can have the following properties:","default":null,"optional":false,"rest":false,"properties":[{"name":"filePath","type":{"text":"string","links":[{"name":"string","href":"https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#string_type","start":0,"end":6}]},"description":"the path to the history file","default":null,"optional":false,"rest":false,"properties":[]},{"name":"size","type":{"text":"number","links":[{"name":"number","href":"https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#number_type","start":0,"end":6}]},"description":"Maximum number of history lines retained. To disable\nthe history set this value to `0`. This option makes sense only if\n`terminal` is set to `true` by the user or by an internal `output` check,\notherwise the history caching mechanism is not initialized at all.","default":"30","optional":true,"rest":false,"properties":[]},{"name":"removeHistoryDuplicates","type":{"text":"boolean","links":[{"name":"boolean","href":"https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#boolean_type","start":0,"end":7}]},"description":"If `true`, when a new input line added\nto the history list duplicates an older one, this removes the older line\nfrom the list.","default":"false","optional":true,"rest":false,"properties":[]},{"name":"onHistoryFileLoaded","type":{"text":"Function","links":[{"name":"Function","href":"https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Function","start":0,"end":8}]},"description":"called when history writes are ready or upon error","default":null,"optional":false,"rest":false,"properties":[{"name":"err","type":{"text":"Error","links":[{"name":"Error","href":"https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Error","start":0,"end":5}]},"description":"","default":null,"optional":false,"rest":false,"properties":[]},{"name":"repl","type":{"text":"repl.REPLServer","links":[{"name":"repl.REPLServer","href":"repl.html#replreplserver","start":0,"end":15}]},"description":"","default":null,"optional":false,"rest":false,"properties":[]}]}]},{"name":"callback","type":{"text":"Function","links":[{"name":"Function","href":"https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Function","start":0,"end":8}]},"description":"called when history writes are ready or upon error\n(Optional if provided as `onHistoryFileLoaded` in `historyConfig`)","default":null,"optional":false,"rest":false,"properties":[{"name":"err","type":{"text":"Error","links":[{"name":"Error","href":"https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Error","start":0,"end":5}]},"description":"","default":null,"optional":false,"rest":false,"properties":[]},{"name":"repl","type":{"text":"repl.REPLServer","links":[{"name":"repl.REPLServer","href":"repl.html#replreplserver","start":0,"end":15}]},"description":"","default":null,"optional":false,"rest":false,"properties":[]}]}],"returns":null},"description":"Initializes a history log file for the REPL instance. When executing the\nNode.js binary and using the command-line REPL, a history file is initialized\nby default. However, this is not the case when creating a REPL\nprogrammatically. Use this method to initialize a history log file when working\nwith REPL instances programmatically.","summary":"Initializes a history log file for the REPL instance. When executing the Node.js binary and using the command-line REPL, a history file is initialized by default. However, this is not the case when creating a REPL programmatically. Use this method to initialize a history log file when working with REPL instances programmatically.","examples":[],"children":[]}]},{"kind":"property","id":"replbuiltinmodules","name":"builtinModules","title":"`repl.builtinModules`","scope":"module","overloadOf":null,"stability":{"index":"0","description":"Deprecated. Use [`module.builtinModules`](module.html#modulebuiltinmodules) instead."},"added":["v14.5.0"],"deprecated":["v24.0.0","v22.16.0"],"removed":[],"napiVersion":[],"changes":[],"type":{"text":"string[]","links":[{"name":"string","href":"https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#string_type","start":0,"end":6}]},"default":null,"description":"A list of the names of some Node.js modules, e.g., `'http'`.\n\nAn automated migration is available ([source](https://github.com/nodejs/userland-migrations/tree/main/recipes/repl-builtin-modules)):\n\n```bash\nnpx codemod@latest @nodejs/repl-builtin-modules\n```","summary":"A list of the names of some Node.js modules, e.g., `'http'`.","examples":[{"language":"bash","displayName":null,"code":"npx codemod@latest @nodejs/repl-builtin-modules"}],"children":[]},{"kind":"method","id":"replstartoptions","name":"start","title":"`repl.start([options])`","scope":"module","overloadOf":null,"stability":null,"added":["v0.1.91"],"deprecated":[],"removed":[],"napiVersion":[],"changes":[{"versions":["v25.9.0"],"prUrl":"https://github.com/nodejs/node/pull/62188","commit":null,"description":"The `handleError` parameter has been added."},{"versions":["v24.1.0"],"prUrl":"https://github.com/nodejs/node/pull/58003","commit":null,"description":"Added the possibility to add/edit/remove multilines while adding a multiline command."},{"versions":["v24.0.0"],"prUrl":"https://github.com/nodejs/node/pull/57400","commit":null,"description":"The multi-line indicator is now \"|\" instead of \"...\". Added support for multi-line history. It is now possible to \"fix\" multi-line commands with syntax errors by visiting the history and editing the command. When visiting the multiline history from an old node version, the multiline structure is not preserved."},{"versions":["v13.4.0","v12.17.0"],"prUrl":"https://github.com/nodejs/node/pull/30811","commit":null,"description":"The `preview` option is now available."},{"versions":["v12.0.0"],"prUrl":"https://github.com/nodejs/node/pull/26518","commit":null,"description":"The `terminal` option now follows the default description in all cases and `useColors` checks `hasColors()` if available."},{"versions":["v10.0.0"],"prUrl":"https://github.com/nodejs/node/pull/19187","commit":null,"description":"The `REPL_MAGIC_MODE` `replMode` was removed."},{"versions":["v6.3.0"],"prUrl":"https://github.com/nodejs/node/pull/6635","commit":null,"description":"The `breakEvalOnSigint` option is supported now."},{"versions":["v5.8.0"],"prUrl":"https://github.com/nodejs/node/pull/5388","commit":null,"description":"The `options` parameter is optional now."}],"signature":{"parameters":[{"name":"options","type":{"text":"Object | string","links":[{"name":"Object","href":"https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Object","start":0,"end":6},{"name":"string","href":"https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#string_type","start":9,"end":15}]},"description":"","default":null,"optional":true,"rest":false,"properties":[{"name":"prompt","type":{"text":"string","links":[{"name":"string","href":"https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#string_type","start":0,"end":6}]},"description":"The input prompt to display.","default":"`'> '` (with a trailing space)","optional":true,"rest":false,"properties":[]},{"name":"input","type":{"text":"stream.Readable","links":[{"name":"stream.Readable","href":"stream.html#class-streamreadable","start":0,"end":15}]},"description":"The `Readable` stream from which REPL input will\nbe read.","default":"process.stdin","optional":true,"rest":false,"properties":[]},{"name":"output","type":{"text":"stream.Writable","links":[{"name":"stream.Writable","href":"stream.html#class-streamwritable","start":0,"end":15}]},"description":"The `Writable` stream to which REPL output will\nbe written.","default":"process.stdout","optional":true,"rest":false,"properties":[]},{"name":"terminal","type":{"text":"boolean","links":[{"name":"boolean","href":"https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#boolean_type","start":0,"end":7}]},"description":"If `true`, specifies that the `output` should be\ntreated as a TTY terminal.","default":"checking the value of the `isTTY` property on the `output` stream upon instantiation","optional":true,"rest":false,"properties":[]},{"name":"eval","type":{"text":"Function","links":[{"name":"Function","href":"https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Function","start":0,"end":8}]},"description":"The function to be used when evaluating each given line\nof input.","default":"an async wrapper for the JavaScript `eval()` function. An `eval` function can error with `repl.Recoverable` to indicate the input was incomplete and prompt for additional lines. See the custom evaluation functions section for more details","optional":true,"rest":false,"properties":[]},{"name":"useColors","type":{"text":"boolean","links":[{"name":"boolean","href":"https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#boolean_type","start":0,"end":7}]},"description":"If `true`, specifies that the default `writer`\nfunction should include ANSI color styling to REPL output. If a custom\n`writer` function is provided then this has no effect.","default":"checking color support on the `output` stream if the REPL instance's `terminal` value is `true`","optional":true,"rest":false,"properties":[]},{"name":"useGlobal","type":{"text":"boolean","links":[{"name":"boolean","href":"https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#boolean_type","start":0,"end":7}]},"description":"If `true`, specifies that the default evaluation\nfunction will use the JavaScript `global` as the context as opposed to\ncreating a new separate context for the REPL instance. The node CLI REPL\nsets this value to `true`.","default":"false","optional":true,"rest":false,"properties":[]},{"name":"ignoreUndefined","type":{"text":"boolean","links":[{"name":"boolean","href":"https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#boolean_type","start":0,"end":7}]},"description":"If `true`, specifies that the default writer\nwill not output the return value of a command if it evaluates to\n`undefined`.","default":"false","optional":true,"rest":false,"properties":[]},{"name":"writer","type":{"text":"Function","links":[{"name":"Function","href":"https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Function","start":0,"end":8}]},"description":"The function to invoke to format the output of each\ncommand before writing to `output`.","default":"util.inspect()","optional":true,"rest":false,"properties":[]},{"name":"completer","type":{"text":"Function","links":[{"name":"Function","href":"https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Function","start":0,"end":8}]},"description":"An optional function used for custom Tab auto\ncompletion. See [`readline.InterfaceCompleter`](readline.html#use-of-the-completer-function) for an example.","default":null,"optional":false,"rest":false,"properties":[]},{"name":"replMode","type":{"text":"symbol","links":[{"name":"symbol","href":"https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#symbol_type","start":0,"end":6}]},"description":"A flag that specifies whether the default evaluator\nexecutes all JavaScript commands in strict mode or default (sloppy) mode.\nAcceptable values are:","default":null,"optional":false,"rest":false,"properties":[{"name":"repl.REPL_MODE_SLOPPY","type":null,"description":"to evaluate expressions in sloppy mode.","default":null,"optional":false,"rest":false,"properties":[]},{"name":"repl.REPL_MODE_STRICT","type":null,"description":"to evaluate expressions in strict mode. This is\nequivalent to prefacing every repl statement with `'use strict'`.","default":null,"optional":false,"rest":false,"properties":[]}]},{"name":"breakEvalOnSigint","type":{"text":"boolean","links":[{"name":"boolean","href":"https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#boolean_type","start":0,"end":7}]},"description":"Stop evaluating the current piece of code when\n`SIGINT` is received, such as when <kbd>Ctrl</kbd>+<kbd>C</kbd> is pressed.\nThis cannot be used\ntogether with a custom `eval` function.","default":"false","optional":true,"rest":false,"properties":[]},{"name":"preview","type":{"text":"boolean","links":[{"name":"boolean","href":"https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#boolean_type","start":0,"end":7}]},"description":"Defines if the repl prints autocomplete and output\npreviews or not.","default":"`true` with the default eval function and `false` in case a custom eval function is used. If `terminal` is falsy, then there are no previews and the value of `preview` has no effect","optional":true,"rest":false,"properties":[]},{"name":"handleError","type":{"text":"Function","links":[{"name":"Function","href":"https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Function","start":0,"end":8}]},"description":"This function customizes error handling in the REPL.\nIt receives the thrown exception as its first argument and must return one\nof the following values synchronously:","default":null,"optional":false,"rest":false,"properties":[{"name":"'print'","type":null,"description":"to print the error to the output stream (default behavior).","default":null,"optional":false,"rest":false,"properties":[]},{"name":"'ignore'","type":null,"description":"to skip all remaining error handling.","default":null,"optional":false,"rest":false,"properties":[]},{"name":"'unhandled'","type":null,"description":"to treat the exception as fully unhandled. In this case,\nthe error will be passed to process-wide exception handlers, such as\nthe [`'uncaughtException'`](process.html#event-uncaughtexception) event.\nThe `'unhandled'` value may or may not be desirable in situations\nwhere the `REPLServer` instance has been closed, depending on the particular\nuse case.","default":null,"optional":false,"rest":false,"properties":[]}]}]}],"returns":{"type":{"text":"repl.REPLServer","links":[{"name":"repl.REPLServer","href":"repl.html#replreplserver","start":0,"end":15}]},"description":""}},"description":"The `repl.start()` method creates and starts a [`repl.REPLServer`](#class-replserver) instance.\n\nIf `options` is a string, then it specifies the input prompt:\n\n```mjs\nimport repl from 'node:repl';\n\n// a Unix style prompt\nrepl.start('$ ');\n```\n\n```cjs\nconst repl = require('node:repl');\n\n// a Unix style prompt\nrepl.start('$ ');\n```","summary":"The `repl.start()` method creates and starts a `repl.REPLServer` instance.","examples":[{"language":"mjs","displayName":null,"code":"import repl from 'node:repl';\n\n// a Unix style prompt\nrepl.start('$ ');"},{"language":"cjs","displayName":null,"code":"const repl = require('node:repl');\n\n// a Unix style prompt\nrepl.start('$ ');"}],"children":[]},{"kind":"section","id":"the-nodejs-repl","name":"The Node.js REPL","title":"The Node.js REPL","scope":"module","overloadOf":null,"stability":null,"added":[],"deprecated":[],"removed":[],"napiVersion":[],"changes":[],"description":"Node.js itself uses the `node:repl` module to provide its own interactive\ninterface for executing JavaScript. This can be used by executing the Node.js\nbinary without passing any arguments (or by passing the `-i` argument):\n\n```console\n$ node\n> const a = [1, 2, 3];\nundefined\n> a\n[ 1, 2, 3 ]\n> a.forEach((v) => {\n...   console.log(v);\n...   });\n1\n2\n3\n```","summary":"Node.js itself uses the `node:repl` module to provide its own interactive interface for executing JavaScript. This can be used by executing the Node.js binary without passing any arguments (or by passing the `-i` argument):","examples":[{"language":"console","displayName":null,"code":"$ node\n> const a = [1, 2, 3];\nundefined\n> a\n[ 1, 2, 3 ]\n> a.forEach((v) => {\n...   console.log(v);\n...   });\n1\n2\n3"}],"children":[{"kind":"section","id":"environment-variable-options","name":"Environment variable options","title":"Environment variable options","scope":"module","overloadOf":null,"stability":null,"added":[],"deprecated":[],"removed":[],"napiVersion":[],"changes":[],"description":"Various behaviors of the Node.js REPL can be customized using the following\nenvironment variables:\n\n* `NODE_REPL_HISTORY`: When a valid path is given, persistent REPL history\n  will be saved to the specified file rather than `.node_repl_history` in the\n  user's home directory. Setting this value to `''` (an empty string) will\n  disable persistent REPL history. Whitespace will be trimmed from the value.\n  On Windows platforms environment variables with empty values are invalid so\n  set this variable to one or more spaces to disable persistent REPL history.\n* `NODE_REPL_HISTORY_SIZE`: Controls how many lines of history will be\n  persisted if history is available. Must be a positive number.\n  **Default:** `1000`.\n* `NODE_REPL_MODE`: May be either `'sloppy'` or `'strict'`. **Default:**\n  `'sloppy'`, which will allow non-strict mode code to be run.","summary":"Various behaviors of the Node.js REPL can be customized using the following environment variables:","examples":[],"children":[]},{"kind":"section","id":"persistent-history","name":"Persistent history","title":"Persistent history","scope":"module","overloadOf":null,"stability":null,"added":[],"deprecated":[],"removed":[],"napiVersion":[],"changes":[],"description":"By default, the Node.js REPL will persist history between `node` REPL sessions\nby saving inputs to a `.node_repl_history` file located in the user's home\ndirectory. This can be disabled by setting the environment variable\n`NODE_REPL_HISTORY=''`.","summary":"By default, the Node.js REPL will persist history between `node` REPL sessions by saving inputs to a `.node_repl_history` file located in the user's home directory. This can be disabled by setting the environment variable `NODE_REPL_HISTORY=''`.","examples":[],"children":[]},{"kind":"section","id":"using-the-nodejs-repl-with-advanced-line-editors","name":"Using the Node.js REPL with advanced line-editors","title":"Using the Node.js REPL with advanced line-editors","scope":"module","overloadOf":null,"stability":null,"added":[],"deprecated":[],"removed":[],"napiVersion":[],"changes":[],"description":"For advanced line-editors, start Node.js with the environment variable\n`NODE_NO_READLINE=1`. This will start the main and debugger REPL in canonical\nterminal settings, which will allow use with `rlwrap`.\n\nFor example, the following can be added to a `.bashrc` file:\n\n```bash\nalias node=\"env NODE_NO_READLINE=1 rlwrap node\"\n```","summary":"For advanced line-editors, start Node.js with the environment variable `NODE_NO_READLINE=1`. This will start the main and debugger REPL in canonical terminal settings, which will allow use with `rlwrap`.","examples":[{"language":"bash","displayName":null,"code":"alias node=\"env NODE_NO_READLINE=1 rlwrap node\""}],"children":[]},{"kind":"section","id":"starting-multiple-repl-instances-in-the-same-process","name":"Starting multiple REPL instances in the same process","title":"Starting multiple REPL instances in the same process","scope":"module","overloadOf":null,"stability":null,"added":[],"deprecated":[],"removed":[],"napiVersion":[],"changes":[],"description":"It is possible to create and run multiple REPL instances against a single\nrunning instance of Node.js that share a single `global` object (by setting\nthe `useGlobal` option to `true`) but have separate I/O interfaces.\n\nThe following example, for instance, provides separate REPLs on `stdin`, a Unix\nsocket, and a TCP socket, all sharing the same `global` object:\n\n```mjs\nimport net from 'node:net';\nimport repl from 'node:repl';\nimport process from 'node:process';\nimport fs from 'node:fs';\n\nlet connections = 0;\n\nrepl.start({\n  prompt: 'Node.js via stdin> ',\n  useGlobal: true,\n  input: process.stdin,\n  output: process.stdout,\n});\n\nconst unixSocketPath = '/tmp/node-repl-sock';\n\n// If the socket file already exists let's remove it\nfs.rmSync(unixSocketPath, { force: true });\n\nnet.createServer((socket) => {\n  connections += 1;\n  repl.start({\n    prompt: 'Node.js via Unix socket> ',\n    useGlobal: true,\n    input: socket,\n    output: socket,\n  }).on('exit', () => {\n    socket.end();\n  });\n}).listen(unixSocketPath);\n\nnet.createServer((socket) => {\n  connections += 1;\n  repl.start({\n    prompt: 'Node.js via TCP socket> ',\n    useGlobal: true,\n    input: socket,\n    output: socket,\n  }).on('exit', () => {\n    socket.end();\n  });\n}).listen(5001);\n```\n\n```cjs\nconst net = require('node:net');\nconst repl = require('node:repl');\nconst fs = require('node:fs');\n\nlet connections = 0;\n\nrepl.start({\n  prompt: 'Node.js via stdin> ',\n  useGlobal: true,\n  input: process.stdin,\n  output: process.stdout,\n});\n\nconst unixSocketPath = '/tmp/node-repl-sock';\n\n// If the socket file already exists let's remove it\nfs.rmSync(unixSocketPath, { force: true });\n\nnet.createServer((socket) => {\n  connections += 1;\n  repl.start({\n    prompt: 'Node.js via Unix socket> ',\n    useGlobal: true,\n    input: socket,\n    output: socket,\n  }).on('exit', () => {\n    socket.end();\n  });\n}).listen(unixSocketPath);\n\nnet.createServer((socket) => {\n  connections += 1;\n  repl.start({\n    prompt: 'Node.js via TCP socket> ',\n    useGlobal: true,\n    input: socket,\n    output: socket,\n  }).on('exit', () => {\n    socket.end();\n  });\n}).listen(5001);\n```\n\nRunning this application from the command line will start a REPL on stdin.\nOther REPL clients may connect through the Unix socket or TCP socket. `telnet`,\nfor instance, is useful for connecting to TCP sockets, while `socat` can be used\nto connect to both Unix and TCP sockets.\n\nBy starting a REPL from a Unix socket-based server instead of stdin, it is\npossible to connect to a long-running Node.js process without restarting it.","summary":"It is possible to create and run multiple REPL instances against a single running instance of Node.js that share a single `global` object (by setting the `useGlobal` option to `true`) but have separate I/O interfaces.","examples":[{"language":"mjs","displayName":null,"code":"import net from 'node:net';\nimport repl from 'node:repl';\nimport process from 'node:process';\nimport fs from 'node:fs';\n\nlet connections = 0;\n\nrepl.start({\n  prompt: 'Node.js via stdin> ',\n  useGlobal: true,\n  input: process.stdin,\n  output: process.stdout,\n});\n\nconst unixSocketPath = '/tmp/node-repl-sock';\n\n// If the socket file already exists let's remove it\nfs.rmSync(unixSocketPath, { force: true });\n\nnet.createServer((socket) => {\n  connections += 1;\n  repl.start({\n    prompt: 'Node.js via Unix socket> ',\n    useGlobal: true,\n    input: socket,\n    output: socket,\n  }).on('exit', () => {\n    socket.end();\n  });\n}).listen(unixSocketPath);\n\nnet.createServer((socket) => {\n  connections += 1;\n  repl.start({\n    prompt: 'Node.js via TCP socket> ',\n    useGlobal: true,\n    input: socket,\n    output: socket,\n  }).on('exit', () => {\n    socket.end();\n  });\n}).listen(5001);"},{"language":"cjs","displayName":null,"code":"const net = require('node:net');\nconst repl = require('node:repl');\nconst fs = require('node:fs');\n\nlet connections = 0;\n\nrepl.start({\n  prompt: 'Node.js via stdin> ',\n  useGlobal: true,\n  input: process.stdin,\n  output: process.stdout,\n});\n\nconst unixSocketPath = '/tmp/node-repl-sock';\n\n// If the socket file already exists let's remove it\nfs.rmSync(unixSocketPath, { force: true });\n\nnet.createServer((socket) => {\n  connections += 1;\n  repl.start({\n    prompt: 'Node.js via Unix socket> ',\n    useGlobal: true,\n    input: socket,\n    output: socket,\n  }).on('exit', () => {\n    socket.end();\n  });\n}).listen(unixSocketPath);\n\nnet.createServer((socket) => {\n  connections += 1;\n  repl.start({\n    prompt: 'Node.js via TCP socket> ',\n    useGlobal: true,\n    input: socket,\n    output: socket,\n  }).on('exit', () => {\n    socket.end();\n  });\n}).listen(5001);"}],"children":[]},{"kind":"section","id":"examples","name":"Examples","title":"Examples","scope":"module","overloadOf":null,"stability":null,"added":[],"deprecated":[],"removed":[],"napiVersion":[],"changes":[],"description":"","summary":"","examples":[],"children":[{"kind":"section","id":"full-featured-terminal-repl-over-netserver-and-netsocket","name":"Full-featured \"terminal\" REPL over net.Server and net.Socket","title":"Full-featured \"terminal\" REPL over `net.Server` and `net.Socket`","scope":"module","overloadOf":null,"stability":null,"added":[],"deprecated":[],"removed":[],"napiVersion":[],"changes":[],"description":"This is an example on how to run a \"full-featured\" (terminal) REPL using\n[`net.Server`](net.html#class-netserver) and [`net.Socket`](net.html#class-netsocket)\n\nThe following script starts an HTTP server on port `1337` that allows\nclients to establish socket connections to its REPL instance.\n\n```mjs\n// repl-server.js\nimport repl from 'node:repl';\nimport net from 'node:net';\n\nnet\n  .createServer((socket) => {\n    const r = repl.start({\n      prompt: `socket ${socket.remoteAddress}:${socket.remotePort}> `,\n      input: socket,\n      output: socket,\n      terminal: true,\n      useGlobal: false,\n    });\n    r.on('exit', () => {\n      socket.end();\n    });\n    r.context.socket = socket;\n  })\n  .listen(1337);\n```\n\n```cjs\n// repl-server.js\nconst repl = require('node:repl');\nconst net = require('node:net');\n\nnet\n  .createServer((socket) => {\n    const r = repl.start({\n      prompt: `socket ${socket.remoteAddress}:${socket.remotePort}> `,\n      input: socket,\n      output: socket,\n      terminal: true,\n      useGlobal: false,\n    });\n    r.on('exit', () => {\n      socket.end();\n    });\n    r.context.socket = socket;\n  })\n  .listen(1337);\n```\n\nWhile the following implements a client that can create a socket connection\nwith the above defined server over port `1337`.\n\n```mjs\n// repl-client.js\nimport net from 'node:net';\nimport process from 'node:process';\n\nconst sock = net.connect(1337);\n\nprocess.stdin.pipe(sock);\nsock.pipe(process.stdout);\n\nsock.on('connect', () => {\n  process.stdin.resume();\n  process.stdin.setRawMode(true);\n});\n\nsock.on('close', () => {\n  process.stdin.setRawMode(false);\n  process.stdin.pause();\n  sock.removeListener('close', done);\n});\n\nprocess.stdin.on('end', () => {\n  sock.destroy();\n  console.log();\n});\n\nprocess.stdin.on('data', (b) => {\n  if (b.length === 1 && b[0] === 4) {\n    process.stdin.emit('end');\n  }\n});\n```\n\n```cjs\n// repl-client.js\nconst net = require('node:net');\n\nconst sock = net.connect(1337);\n\nprocess.stdin.pipe(sock);\nsock.pipe(process.stdout);\n\nsock.on('connect', () => {\n  process.stdin.resume();\n  process.stdin.setRawMode(true);\n});\n\nsock.on('close', () => {\n  process.stdin.setRawMode(false);\n  process.stdin.pause();\n  sock.removeListener('close', done);\n});\n\nprocess.stdin.on('end', () => {\n  sock.destroy();\n  console.log();\n});\n\nprocess.stdin.on('data', (b) => {\n  if (b.length === 1 && b[0] === 4) {\n    process.stdin.emit('end');\n  }\n});\n```\n\nTo run the example open two different terminals on your machine, start the server\nwith `node repl-server.js` in one terminal and `node repl-client.js` on the other.\n\nOriginal code from <https://gist.github.com/TooTallNate/2209310>.","summary":"This is an example on how to run a \"full-featured\" (terminal) REPL using `net.Server` and `net.Socket`","examples":[{"language":"mjs","displayName":null,"code":"// repl-server.js\nimport repl from 'node:repl';\nimport net from 'node:net';\n\nnet\n  .createServer((socket) => {\n    const r = repl.start({\n      prompt: `socket ${socket.remoteAddress}:${socket.remotePort}> `,\n      input: socket,\n      output: socket,\n      terminal: true,\n      useGlobal: false,\n    });\n    r.on('exit', () => {\n      socket.end();\n    });\n    r.context.socket = socket;\n  })\n  .listen(1337);"},{"language":"cjs","displayName":null,"code":"// repl-server.js\nconst repl = require('node:repl');\nconst net = require('node:net');\n\nnet\n  .createServer((socket) => {\n    const r = repl.start({\n      prompt: `socket ${socket.remoteAddress}:${socket.remotePort}> `,\n      input: socket,\n      output: socket,\n      terminal: true,\n      useGlobal: false,\n    });\n    r.on('exit', () => {\n      socket.end();\n    });\n    r.context.socket = socket;\n  })\n  .listen(1337);"},{"language":"mjs","displayName":null,"code":"// repl-client.js\nimport net from 'node:net';\nimport process from 'node:process';\n\nconst sock = net.connect(1337);\n\nprocess.stdin.pipe(sock);\nsock.pipe(process.stdout);\n\nsock.on('connect', () => {\n  process.stdin.resume();\n  process.stdin.setRawMode(true);\n});\n\nsock.on('close', () => {\n  process.stdin.setRawMode(false);\n  process.stdin.pause();\n  sock.removeListener('close', done);\n});\n\nprocess.stdin.on('end', () => {\n  sock.destroy();\n  console.log();\n});\n\nprocess.stdin.on('data', (b) => {\n  if (b.length === 1 && b[0] === 4) {\n    process.stdin.emit('end');\n  }\n});"},{"language":"cjs","displayName":null,"code":"// repl-client.js\nconst net = require('node:net');\n\nconst sock = net.connect(1337);\n\nprocess.stdin.pipe(sock);\nsock.pipe(process.stdout);\n\nsock.on('connect', () => {\n  process.stdin.resume();\n  process.stdin.setRawMode(true);\n});\n\nsock.on('close', () => {\n  process.stdin.setRawMode(false);\n  process.stdin.pause();\n  sock.removeListener('close', done);\n});\n\nprocess.stdin.on('end', () => {\n  sock.destroy();\n  console.log();\n});\n\nprocess.stdin.on('data', (b) => {\n  if (b.length === 1 && b[0] === 4) {\n    process.stdin.emit('end');\n  }\n});"}],"children":[]},{"kind":"section","id":"repl-over-curl","name":"REPL over curl","title":"REPL over `curl`","scope":"module","overloadOf":null,"stability":null,"added":[],"deprecated":[],"removed":[],"napiVersion":[],"changes":[],"description":"This is an example on how to run a REPL instance over [`curl()`](https://curl.haxx.se/docs/manpage.html)\n\nThe following script starts an HTTP server on port `8000` that can accept\na connection established via [`curl()`](https://curl.haxx.se/docs/manpage.html).\n\n```mjs\nimport http from 'node:http';\nimport repl from 'node:repl';\n\nconst server = http.createServer((req, res) => {\n  res.setHeader('content-type', 'multipart/octet-stream');\n\n  repl.start({\n    prompt: 'curl repl> ',\n    input: req,\n    output: res,\n    terminal: false,\n    useColors: true,\n    useGlobal: false,\n  });\n});\n\nserver.listen(8000);\n```\n\n```cjs\nconst http = require('node:http');\nconst repl = require('node:repl');\n\nconst server = http.createServer((req, res) => {\n  res.setHeader('content-type', 'multipart/octet-stream');\n\n  repl.start({\n    prompt: 'curl repl> ',\n    input: req,\n    output: res,\n    terminal: false,\n    useColors: true,\n    useGlobal: false,\n  });\n});\n\nserver.listen(8000);\n```\n\nWhen the above script is running you can then use [`curl()`](https://curl.haxx.se/docs/manpage.html) to connect to\nthe server and connect to its REPL instance by running `curl --no-progress-meter -sSNT. localhost:8000`.\n\n**Warning** This example is intended purely for educational purposes to demonstrate how\nNode.js REPLs can be started using different I/O streams.\nIt should **not** be used in production environments or any context where security\nis a concern without additional protective measures.\nIf you need to implement REPLs in a real-world application, consider alternative\napproaches that mitigate these risks, such as using secure input mechanisms and\navoiding open network interfaces.\n\nOriginal code from <https://gist.github.com/TooTallNate/2053342>.","summary":"This is an example on how to run a REPL instance over `curl()`","examples":[{"language":"mjs","displayName":null,"code":"import http from 'node:http';\nimport repl from 'node:repl';\n\nconst server = http.createServer((req, res) => {\n  res.setHeader('content-type', 'multipart/octet-stream');\n\n  repl.start({\n    prompt: 'curl repl> ',\n    input: req,\n    output: res,\n    terminal: false,\n    useColors: true,\n    useGlobal: false,\n  });\n});\n\nserver.listen(8000);"},{"language":"cjs","displayName":null,"code":"const http = require('node:http');\nconst repl = require('node:repl');\n\nconst server = http.createServer((req, res) => {\n  res.setHeader('content-type', 'multipart/octet-stream');\n\n  repl.start({\n    prompt: 'curl repl> ',\n    input: req,\n    output: res,\n    terminal: false,\n    useColors: true,\n    useGlobal: false,\n  });\n});\n\nserver.listen(8000);"}],"children":[]}]}]}]}