大家好,又见面了,我是你们的朋友全栈君。如果您正在找激活码,请点击查看最新教程,关注关注公众号 “全栈程序员社区” 获取激活教程,可能之前旧版本教程已经失效.最新Idea2022.1教程亲测有效,一键激活。
Jetbrains全家桶1年46,售后保障稳定
REPL
- Design and Features
- Commands and Special Keys
- Default Evaluation
- JavaScript Expressions
- Global and Local Scope
- Accessing Core Node.js Modules
- Assignment of the _ (underscore) variable
- Custom Evaluation Functions
- Recoverable Errors
- Customizing REPL Output
- Class: REPLServer
- Event: ‘exit’
- Event: ‘reset’
- replServer.defineCommand(keyword, cmd)
- replServer.displayPrompt([preserveCursor])
- repl.start([options])
- The Node.js REPL
- Environment Variable Options
- Persistent History
- NODE_REPL_HISTORY_FILE(Deprecated: Use NODE_REPL_HISTORY instead.)
- Using the Node.js REPL with advanced line-editors
- Starting multiple REPL instances against a single running instance
The repl module provides a Read-Eval-Print-Loop (REPL) implementation that is available both as a standalone program or includable in other applications. It can be accessed using:
repl模块提供了一个”读取-求值-输出-循环”(REPL交互式解释器)的实现,它可以作为一个单独的程序,或者包含在其他程序内部。它可以被这样访问:
const repl = require('repl');
Design and Features
设计和特征
The 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.
Instances of repl.REPLServer support automatic completion of inputs, simplistic Emacs-style line editing, multi-line inputs, ANSI-styled output, saving and restoring current REPL session state, error recovery, and customizable evaluation functions.
repl模块由repl.REPLServer类导出。在运行的时候,repl.REPLServer会接受用户输入的单独的行,根据用户定义的求值函数计算这些值,然后输出其结果。输入和输出可能分别来自标准输入和标准输出,或者也可能是任何连接到Node.js上的流。
repl.REPLServer的实例支持输入的自动连接,简化的Emacs风格的行编辑,多行输入,ANSI风格的输出,保存或恢复当前的REPL会话状态,错误恢复,自定义求值函数。
Commands and Special Keys
命令和特殊的键
The following special commands are supported by all REPL instances:
.break
– When in the process of inputting a multi-line expression, entering the.break
command (or pressing the <ctrl>-C key combination) will abort further input or processing of that expression..clear
– Resets the REPL context to an empty object and clears any multi-line expression currently being input..exit
– Close the I/O stream, causing the REPL to exit..help
– Show this list of special commands..save
– Save the current REPL session to a file:> .save ./file/to/save.js
.load
– Load a file into the current REPL session:>.load ./file/to/load.js
.editor
– Enter editor mode (<ctrl>-D to finish, <ctrl>-C to cancel)
下面一些被所有REPL实例支持的专用命令:
.break
– 在输入多行表达式的过程中,输入.break
命令,或者按下<ctrl>-C 组合键,将会中断后续的输入或停止表达式的处理。.clear
– 重置REPL的上下文为一个空对象(实际上等价于.break
,可以算是别名).exit
– 关闭输入/输出流,导致REPL退出。.help
– 显示专用命令列表。.save
– 将当前的REPL会话保持到文件中:> .save ./file/to/save.js
.load
– 将文件加载到当前的REPL会话中:>.load ./file/to/load.js
.editor
– 进入编辑模式(使用<ctrl>-D结束,使用<ctrl>-C来取消)在该模式下使用.exit
并不能退出编辑模式,并且经过实验按<ctrl>-D或<ctrl>-C都会导致命令退出
The following key combinations in the REPL have these special effects:
- <ctrl>-C – When pressed once, has the same effect as the
.break
command. When pressed twice on a blank line, has the same effect as the .exit command.- <ctrl>-D – Has the same effect as the
.exit
command.- <tab> – When pressed on a blank line, displays global and local(scope) variables. When pressed while entering other input, displays relevant autocompletion options.
下面的REPL中的组合键有如下的功效:
- <ctrl>-C – 第一次按的时候和
.break
的效果一样。如果在空白行连续按下两次就和.exit
命令的效果是一样的。 - <ctrl>-D – 跟
.exit
命令有相同的功效。 - <tab> – 当在空白行按下时,会显示全局和本地范围的变量。当键入其他输入时按下的话会显示有关的自动完成选项。
Default Evaluation
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.
默认情况下,所有的repl.REPLServer实例都使用一个求值函数来计算JavaScript表达式,并且提供Node.js内置模块的访问方式。当repl.REPLServer实例被创建的时候,通过替换求值函数可以覆盖默认的行为。
JavaScript Expressions
The default evaluator supports direct evaluation of JavaScript expressions.
Unless otherwise scoped within blocks (e.g. { … }) or functions, variables declared either implicitly or using the var keyword are declared at the global scope.
默认的求值程序支持直接对JavaScript表达式进行求值。
除非另外被在代码块(比如 { … })或者函数中,否则变量要么被隐式声明,要么就是使用声明在全局的关键字。
Global and Local Scope
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. For example:
默认的求值程序提供了访问任何存在于全局范围内的变量的方法。可以通过将变量分配到每一个REPLServer关联的上下文对象的方式,显式地将变量暴露给REPL。
const repl = require('repl');
var msg = 'message';
repl.start('input> ').context.m = msg;
Properties in the context object appear as local within the REPL:
上下文对象的属性表现为REPL的本地变量
$ node repl_test.js
input> m
'message'
input> m = 'xxx'
'xxx'
input> m
'xxx'
It is important to note that context properties are not read-only by default. To specify read-only globals, context properties must be defined using Object.defineProperty():
需要注意的是上下文对象的属性默认不是只读的,要指定全局的只读属性,上下文属性必须使用Object.defineProperty()函数定义
const repl = require('repl');
var msg = 'message';
const r = repl.start('input> ');
Object.defineProperty(r.context, 'm', {
configurable: false,
enumerable: true,
value: msg
});
$ node repl_test.js
input> m
'message'
input> m = 'xxx'
'xxx'
input> m
'message'
Object.defineProperty
ECMAScript 262v5带来的新东西,FF把它归入为javaScript 1.8.5的功能之一。
语法为:Object.defineProperty(obj, prop, descriptor)
参数
- obj:目标对象
- prop:需要定义的属性或方法的名字。
- descriptor:目标属性所拥有的特性。
可供定义的特性列表:
- value:属性的值
- writable:如果为false,属性的值就不能被重写。
- get: 一旦目标属性被访问就会调回此方法,并将此方法的运算结果返回用户。
- set:一旦目标属性被赋值,就会调回此方法。
- configurable:如果为false,则任何尝试删除目标属性或修改属性以下特性(writable, configurable, enumerable)的行为将被无效化。
- enumerable:是否能在for…in循环中遍历出来或在Object.keys(obj)中列举出来。
var obj = {name:'chy', age:24};
Object.defineProperty(obj, 'city', {
get:function(){
return city;},
set:function(value){
city=value;},
configurable:true,
enumerable:true
});
//返回 {name: 'city', age:24, city: [Getter/Setter] }
obj.city='FuZhou';
console.log(obj.city);
//输出 FuZhou
for(var v in obj.city) {
console.log(v);
}
/* 输出 name age city */
console.log(Object.keys(obj));
//输出 [ 'name', 'age', 'city' ]
delete obj.city;
console.log(obj.city);
//输出 undefined
Accessing Core Node.js Modules
访问核心的Node.js模块
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(‘fs’).
默认的求值程序在有用到时,会自动将Node.js的核心模块加载进REPL的环境中。举个例子,除非另外声明一个全局或范围变量,否则输入的fs会被认为成是请求global.fs = require(‘fs’)
> fs.createReadStream('./some/file');
Assignment of the _ (underscore) variable
The default evaluator will, by default, assign the result of the most recently evaluated expression to the special variable _ (underscore).
默认的求值程序,默认会将最近一个表达式计算出来的值赋给那个特殊的下划线(_)变量。
> [ 'a', 'b', 'c' ]
[ 'a', 'b', 'c' ]
> _.length
3
> _ += 1
4
> _ = 0
Expression assignment to _ now disabled.
0
> 2
2
> _
0
Explicitly setting _ to a value will disable this behavior.
显式地将下划线(_)设置为某个值将会禁用该行为。
Custom Evaluation Functions
自定义求值函数
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.
The following illustrates a hypothetical example of a REPL that performs translation of text from one language to another:
当一个新的repl.REPLServer被创建的时候,就会提供一个自定义的求值函数。它可以被这样使用,举个例子,来实现完全自定的REPL应用程序。
下面的例子是一个假象的REPL将一种语言转为另一种语言的示例。
const repl = require('repl');
const Translator = require('translator').Translator;
const myTranslator = new Translator('en', 'fr');
function myEval(cmd, context, filename, callback) {
callback(null, myTranslator.translate(cmd));
}
repl.start({prompt: '> ', eval: myEval});
Recoverable Errors
As a user is typing input into the REPL prompt, pressing the <enter> key will send 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:
当用户键入输入信息到REPL提示,按下回车键后,将会把当前行发送到执行函数里。为了支持多行输入,执行函数可以返回一个repl.Recoverable实例,来提供该回调函数
function eval(cmd, context, filename, callback) {
var result;
try {
result = vm.runInThisContext(cmd);
} catch (e) {
if (isRecoverableError(e)) {
return callback(new repl.Recoverable(e));
}
}
callback(null, result);
}
function isRecoverableError(error) {
if (error.name === 'SyntaxError') {
return /^(Unexpected end of input|Unexpected token)/.test(error.message);
}
return false;
}
Customizing REPL Output
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 useColors boolean option can be specified at construction to instruct the default writer to use ANSI style codes to colorize the output from the util.inspect() method.
It is possible to fully customize the output of a repl.REPLServer instance by passing a new function in using the writer option on construction. The following example, for instance, simply converts any input text to upper case:
默认情况下,repl.REPLServer实例在将数据写入到输出流(默认是process.stdout)之前,会使用util.inspect()方法格式化输出数据。是否使用颜色的选项可以在构造函数中指定,来指示默认的撰写器使用ANSI风格代码来给从util.inspect()函数中输出的数据上色。
通过传递一个新的函数给构造函数中的writer选项,完全可以自定义repl.REPLServer实例的输出。下面的例子,例如,简答的将任意输入的字符串转为大写的
const repl = require('repl');
const r = repl.start({prompt: '>', eval: myEval, writer: myWriter});
function myEval(cmd, context, filename, callback) {
callback(null,cmd);
}
function myWriter(output) {
return output.toUpperCase();
}
Class: REPLServer
Added in: v0.1.91
The repl.REPLServer class inherits from the readline.Interface class. Instances of repl.REPLServer are created using the repl.start() method and should not be created directly using the JavaScript new keyword.
repl.REPLServer类从readline.Interface类中继承。repl.REPLServer实例使用repl.start()函数创建,并且它不应该由JavaScript的new关键字来直接创建。
Event: ‘exit’
Added in: v0.7.7
The ‘exit’ event is emitted when the REPL is exited either by receiving the .exit command as input, the user pressing <ctrl>-C twice to signal SIGINT, or by pressing <ctrl>-D to signal ‘end’ on the input stream. The listener callback is invoked without any arguments.
当收到.exit的输入命令,用户连续两次按下<ctrl>-C来触发SIGINT信号,或按下<ctrl>-D来在输入流触发’end’信号时,REPL会退出,同时’exit’事件会被触发。监听器回调函数会被不带参数地被调用。
Event: ‘reset’
Added in: v0.11.0
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.This can be used primarily to re-initialize REPL context to some pre-defined state as illustrated in the following simple example:
当REPL的上下文被重置时,’reset’事件就会被触发。无论何时,当收到.clear
命令作为输入后,它就会被触发。除非REPL正在使用默认的求值程序并且repl.REPLServer是被创建时useGlobal
参数被设置为真。该监听器回调函数被调用时携带一个上下文对象的引用作为其唯一的参数。
它被主要用在重新初始化REPL上下文为某些预定义的状态,如下面的简单例子所示:
const repl = require('repl');
function initializeContext(context) {
context.m = 'test';
}
var r = repl.start({prompt: '>'});
initializeContext(r.context);
r.on('reset', initializeContext);
When this code is executed, the global ‘m’ variable can be modified but then reset to its initial value using the .clear command:
当该代码被执行之后,全局变量m就会被改变,但是当使用.clear
命令的时候又会被重置为它的初始值。
$ ./node example.js
>m
'test'
>m = 1
1
>m
1
>.clear
Clearing context...
>m
'test'
>
replServer.defineCommand(keyword, cmd)
Added in: v0.3.0
- keyword <String> The command keyword (without a leading . character).
- cmd <Object> | <Function> The function to invoke when the command is processed.
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:
- help <String> Help text to be displayed when .help is entered (Optional).
- action <Function> The function to execute, optionally accepting a single string argument.
The following example shows two new commands added to the REPL instance:
- keyword <String> 命令的关键字(不带前导的”.”字符)。
- cmd <Object> | <Function> 命令执行时调用的函数。
replServer.defineCommand()函数是用来向REPL实例中添加一个新的点.
前缀的命令的。当键入点.
然后跟随着这些关键字,对应的命令就会被执行。这些命令要么是一个函数,要么是一个带属性的对象。
- help <String> 当输入
.help
的时候,会显示帮助文本(可选的) - action <Function> 用来执行的函数,可以接受一个字符串参数。
下面的例子显示了两个添加到REPL实例中的新命令:
const repl = require('repl');
var replServer = repl.start({prompt: '> '});
replServer.defineCommand('sayhello', {
help: 'Say hello',
action: function(name) {
this.lineParser.reset();
this.bufferedCommand = '';
console.log(`Hello, ${name}!`);
this.displayPrompt();
}
});
replServer.defineCommand('saybye', function() {
console.log('Goodbye!');
this.close();
});
The new commands can then be used from within the REPL instance:
该新命令之后就可以使用在REPL实例当中了:
> .sayhello Node.js User
Hello, Node.js User!
> .saybye
Goodbye!
replServer.displayPrompt([preserveCursor])
Added in: v0.1.91
- preserveCursor <Boolean>
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.
When multi-line input is being entered, an ellipsis is printed rather than the ‘prompt’.
When preserveCursor is true, the cursor placement will not be reset to 0.
The replServer.displayPrompt() method is primarily intended to be called from within the action function for commands registered using the replServer.defineCommand() method.
replServer.displayPrompt()函数为REPL实例做好接收用户输入的准备,将配置好的提示打印到输出流新的一行,然后恢复输入流来接收新的输入。
当多行输入被键入的时候,会打印一个省略号而不是提示字符
replServer.displayPrompt()函数主要是在使用replServer.defineCommand()为命令注册功能函数时被调用。
repl.start([options])
Added in: v0.1.91
- options <Object>
- prompt <String> The input prompt to display. Defaults to >.
- input <Readable> The Readable stream from which REPL input will be read. Defaults to process.stdin.
- output <Writable> The Writable stream to which REPL output will be written. Defaults to process.stdout.
- terminal <boolean> If true, specifies that the output should be treated as a a TTY terminal, and have ANSI/VT100 escape codes written to it. Defaults to checking the value of the isTTY property on the output stream upon instantiation.
- eval <Function> The function to be used when evaluating each given line of input. Defaults to 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.
- useColors <boolean> If true, specifies that the default writer function should include ANSI color styling to REPL output. If a custom writer function is provided then this has no effect. Defaults to the REPL instances terminal value.
- useGlobal <boolean> If true, specifies that the default evaluation function will use the JavaScript global as the context as opposed to creating a new separate context for the REPL instance. Defaults to false.
- ignoreUndefined <boolean> If true, specifies that the default writer will not output the return value of a command if it evaluates to undefined. Defaults to false.
- writer <Function> The function to invoke to format the output of each command before writing to output. Defaults to util.inspect().
- completer <Function> An optional function used for custom Tab auto completion. See readline.InterfaceCompleter for an example.
- replMode – A flag that specifies whether the default evaluator executes all JavaScript commands in strict mode, default mode, or a hybrid mode (“magic” mode.) Acceptable values are:
- repl.REPL_MODE_SLOPPY – evaluates expressions in sloppy mode.
- repl.REPL_MODE_STRICT – evaluates expressions in strict mode. This is equivalent to prefacing every repl statement with ‘use strict’.
- repl.REPL_MODE_MAGIC – attempt to evaluates expressions in default mode. If expressions fail to parse, re-try in strict mode.
- breakEvalOnSigint – Stop evaluating the current piece of code when SIGINT is received, i.e. Ctrl+C is pressed. This cannot be used together with a custom eval function. Defaults to false.
The repl.start() method creates and starts a repl.REPLServer instance.
-
options <Object>
- prompt <String> 待显示的输入提示符。 默认是 >。
-
input <Readable> REPL中可读取的输入流,默认是process.stdin.
-
output <Writable> REPL中可写的输出流,默认是process.stdout。
- terminal <boolean> 如果为真,指定的输出会被当成一个TTY终端,并且会写入ANSI/VT100的转移代码。默认是在输出流实例上校验
isTTY
属性。 - eval <Function>当执行输入的每一行时需要改函数。默认是对JavaScript的eval()函数的异步封装。eval()函数也可能会产生repl.recoverable错误来指示输入不完整,然后提示附加行。
- useColors <boolean>如果为真,则指定默认的
writer
函数在向REPL输出时应该包含ANSI颜色风格。如果提供了一个第三方的writer
函数,它就没有任何影响。默认被设置为REPL实例的terminal
值。 - useGlobal <boolean> 如果为真,指定的默认求值函数会使用JavaScript的
global
作为上下文变量,而不是为REPL实例创建一个新的隔离的上下文变量。默认是假。 - ignoreUndefined <boolean> 如果为真,指定默认的写入器当命令的执行结果为
undefined
时不会输出。默认是false。 - writer <Function>在写入到输出流之前,调用来格式化每一条输出命令的函数。默认使用util.inspect()。
- completer <Function> 一个可选的函数,当自定义Tab键自动完成时使用。详见
readline.InterfaceCompleter
的例子。 - replMode – 一个标志指定是否默认的求值程序使用严格的模式执行所有的JavaScript,默认的模式,也可以说是一个混合模式(”magic” mode)。可接受的参数如下:
- repl.REPL_MODE_SLOPPY – 使用懒散的方式执行表达式。
- repl.REPL_MODE_STRICT – 使用严格的方式执行表达式。
- repl.REPL_MODE_MAGIC – 尝试使用默认的方式去执行表达式。如果表达式解析错误,重新使用严格模式解析。
- breakEvalOnSigint – 当收到SIGINT时,停止执行当前的代码块,比如按下
Ctrl+C
。它不能与一个自定义的eval
函数一起使用。默认是假。
repl.start()函数创建并启动了一个REPLServer实例。
The Node.js REPL
Node.js itself uses the repl module to provide its own interactive interface for executing JavaScript. This can used by executing the Node.js binary without passing any arguments (or by passing the -i argument):
Node.js它自己使用repl模块为执行JavaScript来提供它自己的交互性接口。它可以用来执行不带任何参数的Node.js二进制代码(或者传递-i参数)
$ node
> a = [1, 2, 3];
[ 1, 2, 3 ]
> a.forEach((v) => {
... console.log(v);
... });
1
2
3
Environment Variable Options
Various behaviors of the Node.js REPL can be customized using the following environment variables:
- NODE_REPL_HISTORY – When a valid path is given, persistent REPL history will be saved to the specified file rather than .node_repl_history in the user’s home directory. Setting this value to “” will disable persistent REPL history. Whitespace will be trimmed from the value.
- NODE_REPL_HISTORY_SIZE – Defaults to 1000. Controls how many lines of history will be persisted if history is available. Must be a positive number.
- NODE_REPL_MODE – May be any of sloppy, strict, or magic. Defaults to magic, which will automatically run “strict mode only” statements in strict mode.
通过使用如下的变量,Node.js的REPL的各种行为都可以被自定义化。
- NODE_REPL_HISTORY – 当给定一个合法路径是,会永久的将REPL历史记录报错到这个指定的文件中,而不是用户家目录中的
.node_repl_histor
文件。将该变量设置为""
,可以禁止报错REPL历史记录。空格会从该变量中被删去。 - NODE_REPL_HISTORY_SIZE – 默认是1000. 如果存在历史记录的话,控制总共可以存储多少行记录。该值必须是一个正数。
- NODE_REPL_MODE – 可以是
sloppy
,strict
或magic
中的一个。默认是magic
。在strict模式下时,会自动只运行严格的语句。
Persistent History
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 variableNODE_REPL_HISTORY=""
.
默认情况下,Node,js的REPL会通过将输入保存到用户家目录下的一个.node_repl_history
历史记录文件中持久化地保存REPL会话历史。它可以通过设置环境变量NODE_REPL_HISTORY=""
,来禁用。
NODE_REPL_HISTORY_FILE
Added in: v2.0.0
Deprecated since: v3.0.0-Deprecated: Use NODE_REPL_HISTORY instead.Previously in Node.js/io.js v2.x, REPL history was controlled by using a
NODE_REPL_HISTORY_FILE
environment variable, and the history was saved in JSON format. This variable has now been deprecated, and the old JSON REPL history file will be automatically converted to a simplified plain text format. This new file will be saved to either the user’s home directory, or a directory defined by theNODE_REPL_HISTORY
variable, as documented in theEnvironment Variable Options
.
从v3.0.0版本以后就被废弃了:使用NODE_REPL_HISTORY
来代替。
之前在Node.js/io.js v2.x中,REPL历史记录被NODE_REPL_HISTORY_FILE
环境变量所控制,并且历史记录被保存为JSON格式。这个变量现在已经被废弃了。并且旧的JSON格式的REPL历史记录会自动被转为纯文本格式。新的文件要么被保存在用户的家目录,要么被保存在NODE_REPL_HISTORY
变量定义的目录中,定义在Environment Variable Options
中。
Using the Node.js REPL with advanced line-editors
For advanced line-editors, start Node.js with the environmental variable
NODE_NO_READLINE=1
. This will start the main and debugger REPL in canonical terminal settings which will allow you to use withrlwrap
.For example, you could add this to your bashrc file:
为了使用更先进的行编辑器,可以以带环境变量NODE_NO_READLINE=1
的方式启动Node.js。它会在一个典型的允许你使用rlwrap
的终端设置上启动主函数并且调试REPL。
举个例子,你可以将这个添加到bashrc文件中。
alias node="env NODE_NO_READLINE=1 rlwrap node"
安装rlwrap的初衷:
在Windows 下使用SQLPLUS都是可以使用上下左右方向键前后左右翻转移动,每句命令也是可以往前或往后修改,但Linux 下却不行,一直要使用SQLPLUS,这样做有些难受,网上查询了下,可以使用rlwrap 解决
Starting multiple REPL instances against a single running instance
It is possible to create and run multiple REPL instances against a single running instance of Node.js that share a single global object but have separate I/O interfaces.
The following example, for instance, provides separate REPLs on stdin, a Unix socket, and a TCP socket:
它可以创建和执行多个REPL实例,而不是在Node.js上只能运行一个。它们共享同一个全局对象,但是并没有分隔开的I/O接口。
下面的实例,举个例子,提供了一个隔离的REPLs在stdin
、Unix套接字和TCP套接字上。
const net = require('net');
const repl = require('repl');
var connections = 0;
repl.start({
prompt: 'Node.js via stdin> ',
input: process.stdin,
output: process.stdout
});
net.createServer((socket) => { connections += 1; repl.start({ prompt: 'Node.js via Unix socket> ', input: socket, output: socket }).on('exit', () => { socket.end(); }); }).listen('/tmp/node-repl-sock'); net.createServer((socket) => { connections += 1; repl.start({ prompt: 'Node.js via TCP socket> ', input: socket, output: socket }).on('exit', () => { socket.end(); }); }).listen(5001);
Running this application from the command line will start a REPL on stdin. Other REPL clients may connect through the Unix socket or TCP socket. telnet, for instance, is useful for connecting to TCP sockets, while socat can be used to connect to both Unix and TCP sockets.
By starting a REPL from a Unix socket-based server instead of stdin, it is possible to connect to a long-running Node.js process without restarting it.
For an example of running a “full-featured” (terminal) REPL over a net.Server and net.Socket instance, see: https://gist.github.com/2209310
For an example of running a REPL instance over curl(1), see: https://gist.github.com/2053342
从命令行中运行这个程序会在stdin中启动一个REPL。其它REPL客户端会连到Unix套接字或TCP套接字上。telnet,举个例子,对于连接TCP套接字非常有用,它既可以用来连接Unix也可以用来来连接TCP套接字。
通过启动一个基于Unix的套接字服务器而不是stdin,可以连接到一个持久运行的Node.js进程中,而不用重启它。
通过net.Server和net.Socket实例运行全特性(终端)的REPL的例子,参看:https://gist.github.com/2209310
通过curl(1)运行REPL实例的例子,参看:https://gist.github.com/2053342
发布者:全栈程序员-用户IM,转载请注明出处:https://javaforall.cn/213275.html原文链接:https://javaforall.cn
【正版授权,激活自己账号】: Jetbrains全家桶Ide使用,1年售后保障,每天仅需1毛
【官方授权 正版激活】: 官方授权 正版激活 支持Jetbrains家族下所有IDE 使用个人JB账号...