1.REPL(Read-Eval-Print-Loop)
交互式运行环境,开发者可以在该运行环境中输入任何js表达式,当用户按下回车后,REPL运行环境将显示该表达式的运行结果。
如何自定义并启动REPL运行环境
nodejs框架为REPL运行环境提供来那些命令以及命令的作用
如何使用REPL环境/如何在该环境进行测试js表达式
2.1REPL运行环境中操作变量
输入
node
回车,就进入REPL
环境,环境标志为>
let foo="bar";
//会出现 undefined,然后再去访问 foo 则会输出答案 bar
//而直接fo="bar"则直接输出答案 bar
出现两种不同的结果是因为REPL
内部环境使用eval
函数来评估该表达式的执行结果。
> obj=new Object()
{}
> obj.name="kxf";obj.age=22;
22
> obj.name
'kxf'
> obj
{ name: 'kxf', age: 22 }
如果添加函数则直接会显示[Function]
,因为function
里面通常会有大量的逻辑处理。
2.2在REPL中使用下划线(_)字符
_字符代表上一次的执行结果
> a=4
4
> _+1
5
>
2.3在REPL中定义并启动服务器
//不需要使用js文件,直接可以在浏览器上进行访问。
kuangxiengdeMBP:day2-REPL kxf$ node
> let http=require('http')
undefined
> http.createServer(function(req,res){res.writeHead(200,{'Contet-Type':'text/html'});res.write('<head><meta charset="utf-8" /></head>');res.end("你好")}).listen(8080,"127.0.0.1");
Server {
domain:
Domain {
domain: null,
_events:
[Object: null prototype] {
removeListener: [Function: updateExceptionCapture],
newListener: [Function: updateExceptionCapture],
error: [Function: debugDomainError] },
_eventsCount: 3,
_maxListeners: undefined,
members: [] },
_events:
[Object: null prototype] {
request: [Function],
connection: [Function: connectionListener] },
_eventsCount: 2,
_maxListeners: undefined,
_connections: 0,
_handle: null,
_usingWorkers: false,
_workers: [],
_unref: false,
allowHalfOpen: true,
pauseOnConnect: false,
httpAllowHalfOpen: false,
timeout: 120000,
keepAliveTimeout: 5000,
_pendingResponseData: 0,
maxHeadersCount: null,
headersTimeout: 40000,
[Symbol(IncomingMessage)]:
{ [Function: IncomingMessage]
super_:
{ [Function: Readable]
ReadableState: [Function: ReadableState],
super_: [Function],
_fromList: [Function: fromList] } },
[Symbol(ServerResponse)]:
{ [Function: ServerResponse] super_: { [Function: OutgoingMessage] super_: [Function] } },
[Symbol(asyncId)]: -1 }
>
2.4REPL运行环境的上下文对象
在
node.js
中可以使用start()
方法返回被开启的REPL
运行环境,可以为REPL
运行环境指定一个上下文对象,可以将该上下文保存的对象作为REPL
运行环境的全局变量。
//index.js
let repl=require('repl');
let context=repl.start().context;
context.msg="全局变量";
context.testFunction=function(){
console.log(context.msg);
}
然后node index.js
kuangxiengdeMBP:day2-REPL kxf$ node index.js
> msg
'全局变量'
> testFunction()
全局变量
undefined
>
2.5REPL运行环境中的基础指令
.exit:退出REPL
运行环境
.help - 列出使用命令
.break - 退出多行表达式
.clear:用于清除REPL
运行环境的上下文对象中保存的所有变量与对象。
.save filename - 保存当前的 Node REPL 会话到指定文件
.load filename - 载入当前 Node REPL 会话的文件内容。
小结:交互式开发环境REPL
,可以操作变量,可以使用_
来返回上次执行结果,可以自定义并启动服务器,REPL
运行环境中的上下文对象,以及一些基础的指令。这让我想起了在使用浏览器的时候,在控制台表现的结果和这个如出一辙。