天天看點

Node.js REPL子產品

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都會導緻指令退出
Node.js REPL子產品
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:};
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

> _ += 

> _ = 
Expression assignment to _ now disabled.

> 

> _

           
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提示,按下Enter鍵後,将會把目前行發送到執行函數裡。為了支援多行輸入,執行函數可以傳回一個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 = 

>m

>.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 = [, , ];
[ , ,  ]
> a.forEach((v) => {
...   console.log(v);
...   });



           

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 variable

NODE_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 the

NODE_REPL_HISTORY

variable, as documented in the

Environment 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 with

rlwrap

.

For example, you could add this to your bashrc file:

為了使用更先進的行編輯器,可以以帶環境變量

NODE_NO_READLINE=1

的方式啟動Node.js。它會在一個典型的允許你使用

rlwrap

的終端設定上啟動主函數并且調試REPL。

舉個例子,你可以将這個添加到bashrc檔案中。

安裝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 = ;

repl.start({
  prompt: 'Node.js via stdin> ',
  input: process.stdin,
  output: process.stdout
});

net.createServer((socket) => {
  connections += ;
  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 += ;
  repl.start({
    prompt: 'Node.js via TCP socket> ',
    input: socket,
    output: socket
  }).on('exit', () => {
    socket.end();
  });
}).listen();
           

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

繼續閱讀