https://nodejs.org/api/modules.html

现在做一个各种版本的实时新闻页面,想用node.js的socket.io实现,node.js的语法不熟,所以恶补一下。

REPL

#

Stability: 2 - Stable

The 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:

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.

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)
> .editor
// Entering editor mode (^D to finish, ^C to cancel)
function welcome(name) {return `Hello ${name}!`;
}welcome('Node.js User');// ^D
'Hello Node.js User!'
>

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.

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.

JavaScript Expressions#

The default evaluator supports direct evaluation of JavaScript expressions:

> 1 + 1
2
> const m = 2
undefined
> m + 1
3

Unless otherwise scoped within blocks or functions, variables declared either implicitly or using the constlet, or varkeywords are declared at the global scope.

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:

const repl = require('repl');
const msg = 'message';repl.start('> ').context.m = msg;

Properties in the context object appear as local within the REPL:

$ node repl_test.js
> m
'message'

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():

const repl = require('repl');
const msg = 'message';const r = repl.start('> ');
Object.defineProperty(r.context, 'm', {configurable: false,enumerable: true,value: msg
});

Accessing Core Node.js Modules#

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').

> 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). Explicitly setting _ to a value will disable this behavior.

> [ 'a', 'b', 'c' ]
[ 'a', 'b', 'c' ]
> _.length
3
> _ += 1
Expression assignment to _ now disabled.
4
> 1 + 1
2
> _
4

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:

const repl = require('repl');
const { Translator } = require('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 evalfunction. In order to support multi-line input, the eval function can return an instance of repl.Recoverable to the provided callback function:

function myEval(cmd, context, filename, callback) {let 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:

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.

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.

replServer.on('exit', () => {console.log('Received "exit" event from repl!');process.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:

const repl = require('repl');function initializeContext(context) {context.m = 'test';
}const 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 .clearcommand:

$ ./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:

const repl = require('repl');const replServer = repl.start({ prompt: '> ' });
replServer.defineCommand('sayhello', {help: 'Say hello',action(name) {this.bufferedCommand = '';console.log(`Hello, ${name}!`);this.displayPrompt();}
});
replServer.defineCommand('saybye', function saybye() {console.log('Goodbye!');this.close();
});

The new commands can then be used from within the REPL instance:

> .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 promptto 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.

repl.start([options])#

History
  • options <Object> | <string>

    • prompt <string> The input prompt to display. Defaults to > (with a trailing space).
    • 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 terminalvalue.
    • 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. The node CLI REPL sets this value to true. 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 <symbol> A flag that specifies whether the default evaluator executes all JavaScript commands in strict mode or default (sloppy) 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 - This value is deprecated, since enhanced spec compliance in V8 has rendered magic mode unnecessary. It is now equivalent to repl.REPL_MODE_SLOPPY (documented above).
    • 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.

If options is a string, then it specifies the input prompt:

const repl = require('repl');// a Unix style prompt
repl.start('$ ');

The Node.js REPL#

Node.js itself uses the 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):

$ node
> const a = [1, 2, 3];
undefined
> a
[ 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 sloppystrict, or magic. Defaults to sloppy, which will allow non-strict mode code to be run. magic is deprecated and treated as an alias of sloppy.

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_REPL_HISTORY_FILE#

Added in: v2.0.0Deprecated since: v3.0.0
Stability: 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.

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 use with rlwrap.

For example, the following can be added to a .bashrc file:

alias node="env NODE_NO_READLINE=1 rlwrap node"

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 globalobject but have separate I/O interfaces.

The following example, for instance, provides separate REPLs on stdin, a Unix socket, and a TCP socket:

const net = require('net');
const repl = require('repl');
let 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

REPL module相关推荐

  1. Spark开源REST服务——Apache Livy(Spark 客户端)

    文章目录 一.概述 二.Apache Livy模块介绍 1)Client 2)router 3)权限管理 4)生成 Spark App 5)交互式 Driver 6)状态数据存储 三.Apache L ...

  2. Nodejs之require加载机制(模块可以污染全局空间)

    以前就觉得Nodejs的MooTools库很奇怪,因为用他的时候,不需要把require的返回值保存起来,今天实在憋不住,就研究了下,对NodeJs的require机制又有了几分深刻的理解. MooT ...

  3. nodejs系列(二)REPL交互解释 事件循环

    一.REPL交互解释 命令行中输入node启动REPL: > var x =2; undefined > do{x++; ... console.log("x:="+x ...

  4. REPL (read-evaluate-print-loop)概念-读取评估打印循环

    2019独角兽企业重金招聘Python工程师标准>>> 概述 在REPL中,用户输入一个或多个表达式(而不是整个编译单元),REPL评估它们并显示结果.名称read-eval-pri ...

  5. Apache Spark源码走读之16 -- spark repl实现详解

    欢迎转载,转载请注明出处,徽沪一郎. 概要 之所以对spark shell的内部实现产生兴趣全部缘于好奇代码的编译加载过程,scala是需要编译才能执行的语言,但提供的scala repl可以实现代码 ...

  6. python交互模式切换_Python 交互式窗口 (REPL) - Visual Studio | Microsoft Docs

    使用 Python 交互窗口Work with the Python Interactive window 02/11/2019 本文内容 Visual Studio 为每个 Python 环境提供交 ...

  7. 关于module require的学习

    // Jerry 2017-12-9 11:39AM we can currently treat module as a keyword in nodejs environment var conf ...

  8. Module System of Swift (简析 Swift 的模块系统)

    原文地址: http://andelf.github.io/blog/2014/06/19/modules-for-swift/ Swift 中模块是什么?当写下 Swift 中一句 import C ...

  9. await原理 js_「速围」Node.js V14.3.0 发布支持顶级 Await 和 REPL 增强功能

    本周,Nodejs v14.3.0 发布.这个版本包括添加顶级 Await.REPL 增强等功能. REPL 增强 通过自动补全改进对 REPL 的预览支持,例如,下图中当输入 process.ver ...

最新文章

  1. ajax中加上AntiForgeryToken防止CSRF攻击
  2. element更改表格表头、行、指定单元格样式
  3. 转:智能卡测试操作系统技术
  4. 2017计算机三级哪个好考,快速突破2017年计算机三级考试的几大复习阶段
  5. s丅7318是啥芯片_透彻解析LED驱动芯片HT1632C指令集与驱动编程
  6. 百度地图缩放 — 放开手指时地图位置移动问题解决
  7. JavaSE教程_1 安装jdk
  8. 岗位目标_达州苏宁召开2019年度工作规划 与岗位目标责任书签订仪式会议
  9. Oracle怎样导出应收开票,【Oracle|Oracle财务系统应收账款模块操作手册】
  10. python统计大写辅音字母_大写
  11. 在使用btest中的demo中遇到 multiple definition of 的问题!
  12. android 话费充值代码,调用手机话费充值API的SDK编写思路
  13. 机器学习基础整理(第2章) - 模式分类
  14. 做游戏,学编程(C语言) 15 太鼓达人
  15. Python 编程笔记(本人出品,必属精品)
  16. 面向对象开发期末复习概述(二)
  17. 计算机应用提高篇课后答案,计算机应用技能技巧
  18. 计算机windows7更新失败,Win7电脑windows update更新失败如何解决?
  19. 如何在万网购买一个属于自己的域名
  20. 中国大学MOOC-陈越、何钦铭-数据结构-2022春期中考试

热门文章

  1. C++加载lib和dll的方法
  2. 《自然语言处理实战入门》 深度学习组件TensorFlow2.0 ---- 文本数据建模流程
  3. 微信小程序退款功能(详解完整)
  4. html纵向排列图片,ppt版式垂直排列标题与文本
  5. idea报错:fatal: –author ‘user@mail.com’ is not ‘Name ’ and matches no existing author
  6. 在Python应用中Telegram 机器人搭建消息提醒
  7. Fugiat inventore earum unde officia nihil ratione.Аллея развитый юный сынок угроза голубчик.
  8. java计算机毕业设计无线通信基站监控及管理系统源码+系统+数据库+lw文档+mybatis+运行部署
  9. SecureCrt 连接服务器失败 key exchange failed 解决方案
  10. 联想台式计算机光驱启动,联想电脑怎么设置光驱启动【图文】