node.js之REPL

何为REPL

wiki:node

“读取-求值-输出”循环(英语:Read-Eval-Print Loop,简称REPL)是一个简单的,交互式的编程环境。web

node.js官方文档(v0.12.2):编程

REPL既能够做为独立单机程序,也能够被其余的程序包含在内的程序。数组

它提供了一种交互方式,即“执行程序,展示结果”。浏览器

它能够被用做debuggingtesting 或者只是执行操做获得一些结果。session

执行REPL

打开命令行,键入node函数

$ node
>

而后就能够当开发环境使了oop

> var age = 12
undefined
> age
12


> function getAge(){
... console.log(this.age)
... }
undefined

> getAge()
12
undefined

由于REPL环境内部使用eval函数来评估该表达式的执行结果,因此有些东西咱们能够直接这样写,如对象:this

> {a:1,b:2}
{ a: 1, b: 2 }

> [1,2,3,4,5]
[ 1, 2, 3, 4, 5 ]

下划线 _

使用_能够指代上一次的操做执行后的值,好比lua

对象:

> {a:1,b:2,c:3}
{ a: 1, b: 2, c: 3 }

> for(var key in _){
..... console.log('key : ' + key + ',value : ' + _[key]);
..... }

key : a,value : 1
key : b,value : 2
key : c,value : 3
//这里的_指代的是上一次执行操做后的对象

数组:

> [1,2,3,4,5]
[ 1, 2, 3, 4, 5 ] 
> Object.keys(_)                        //这里的_指代的时上一次执行的数组
[ '0', '1', '2', '3', '4' ]             //获取index值

注意  下面的值不是咱们的预期,由于_指代的已经不是原先的数组了!

> _.map(function(k){return _[k]*_[k]})  
[ 0, 1, 4, 9, 16 ]                      //获取元素值

正确的结果:

> [1,2,3,4,5]
[ 1, 2, 3, 4, 5 ]                       //数组
> Object.keys(_).map(function(k){return _[k]*_[k]})
[ 1, 4, 9, 16, 25 ]                     //元素值

内置REPL方法

一些REPL里的方法,经过键入.help能够看到:

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

.break & .clear

做用:中断当前的出入
你想退出你当前的输入环境,使用.break 或者 .clear

> function show(){
... console.log('');
... .clear           //.clear 或 .break
>

.exit

做用:退出REPL ;快捷键:

control + c

直接退出REPL,回到命令行。

.save

将当前REPL中全部会话保存到文件中

> function sum(a,b){
... return a + b;
... }
undefined

> function substract(a,b){
... return a - b;
... }
undefined

> .save calculator.js
Session saved to:calculator.js

.load

加载文件进入到当前的REPL会话。

> .load calculator.js

> function sum(a,b){
... return a + b;
... }
undefined

> function substract(a,b){
... return a - b;
... }
undefined

> sum(3,5)
8

> substract(8,2)
6

最后扯几句

一门语言在运行的时候,须要一个环境,叫作宿主环境。对于JavaScript,宿主环境最多见的是web浏览器。

因此这时的this一般指代的时window

而在nodeREPL中,this指代的是global

> this
{ DTRACE_NET_SERVER_CONNECTION: [Function],
  DTRACE_NET_STREAM_END: [Function],
...

> this === global
true

REPL的优点在于:
- 能够debugging
- 作一些testing
- 快速的实践执行操做

done.
相关文章
相关标签/搜索