利用node.js的REPL学习JavaScript

来自软件实验室
跳转至: 导航搜索

node.js的REPL

REPL(Read-Eval-Print-Loop)是一个交互式环境,比如PostgreSQL的psql。node.js也提供了REPL的交互方式,在debian下面直接执行nodejs即可:

subaochen@debian:~$ nodejs
> .help
.break	Sometimes you get stuck, this gets you out
.clear	Alias for .break
.exit	Exit the repl
.help	Show repl options
.load	Load JS from a file into the REPL session
.save	Save all evaluated commands in this REPL session to a file


常用的REPL交互命令

下划线_

_代表上一个表达式的值,比如:

> [1,2,3,4]
[ 1, 2, 3, 4 ]
> _.length
4
> 

ctrl+c/ctrl+d

ctrl+c等价于.break,终止当前的命令。

ctrl+d等价于.exit,退出RPEL环境。

tab

很有用,列出global/local对象,比如:

> 
Array                 Boolean               Date                  Error                 EvalError             Function              Infinity
JSON                  Math                  NaN                   Number                Object                RangeError            ReferenceError
RegExp                String                SyntaxError           TypeError             URIError              decodeURI             decodeURIComponent
encodeURI             encodeURIComponent    eval                  isFinite              isNaN                 parseFloat            parseInt
undefined             

ArrayBuffer           Buffer                DataView              Float32Array          Float64Array          GLOBAL                Int16Array
Int32Array            Int8Array             Uint16Array           Uint32Array           Uint8Array            Uint8ClampedArray     _
assert                buffer                child_process         clearImmediate        clearInterval         clearTimeout          cluster
console               crypto                dgram                 dns                   domain                escape                events
fs                    global                http                  https                 module                net                   os
path                  process               punycode              querystring           readline              require               root
setImmediate          setInterval           setTimeout            stream                string_decoder        tls                   tty
unescape              url                   util                  vm                    zlib                  

__defineGetter__      __defineSetter__      __lookupGetter__      __lookupSetter__      constructor           hasOwnProperty        isPrototypeOf
propertyIsEnumerable  toLocaleString        toString              valueOf 

.load

加载脚本,相当于C语言的include,这样脚本中的定义、语句等就加入到了当前的会话。比如要《JavaScript权威指南》的例子09.01.range.js,必须先加载06.01.inherit.js,可以这样做:

> .load 06.01.inherit.js
> .load 09.01.range.js


更多信息请参见REPL的官网文档: https://nodejs.org/api/repl.html