一、REPL交互解释
命令行中输入node启动REPL:
> var x =2;
undefined
> do{x++;
... console.log("x:="+x);
... }while(x<6);
x:=3
x:=4
x:=5
x:=6
undefined
>
Ctrl + C退出循环或者当前终端;
> a * b
30
> var c = _
undefined
> console.log(c)
30
下划线(_)变量
可以使用下划线(_)获取表达式的运算结果↑
二、事件循环
这个小demo差点成为我的瓶颈(想想也很可笑的,居然这样了,习惯太差)
//引入 events 模块
//var events = require('events');
////创建 eventEmitter 对象
////var eventEmitter = new events.EventEmitter();
var eventEmitter = new (require('events')).EventEmitter();
//////创建 eventEmitter 对象
//var eventEmitter = new events.EventEmitter();
////绑定事件及事件的处理程序
//eventEmitter.on('eventname',eventHandler);
////触发事件
//eventEmitter.emit('eventname');
//创建事件处理程序
var connectHandler = function connected(){
console.log('第①步--连接成功!');
//触发事件 data_received
eventEmitter.emit('data_received');
var x = 5,y = 3;
console.log("第③步--"+(x+y));
}
兰青色部分必须之前定义
//绑定 connection 事件处理程序
eventEmitter.on('connection',connectHandler);
//使用匿名函数绑定 data_received事件
eventEmitter.on('data_received',function(){
console.log("第②步--数据接收成功!");
})
//触发 connection 事件
eventEmitter.emit("connection");
console.log("第④步--events over!");
E:
ode>node main.js
first--cuccess��
second--data success��
third--8
forth--events over!
E:
ode>node main.js
第①步--连接成功!
第②步--数据接收成功!
第③步--8
第④步--events over!
var events = require("events"); //注意是events,注意s第二个错误
var emitter = new events.EventEmitter();
emitter.on('someEvent',function(arg1, arg2){
console.log('listener1', arg1, arg2);
});
emitter.on('someEvent', function(arg1, arg2){
console.log('listener2', arg1, arg2);
});
emitter.emit('someEvent', 'arg1 参数', 'arg2 参数');
E:
odeevent.js:11 注意封号
emitter.emit('someEvent', 'arg1 鍙傛暟'锛?'arg2 鍙傛暟')锛?
^
SyntaxError: Unexpected token ILLEGAL
at Module._compile (module.js:439:25)
at Object.Module._extensions..js (module.js:474:10)
at Module.load (module.js:356:32)
at Function.Module._load (module.js:312:12)
at Function.Module.runMain (module.js:497:10)
at startup (node.js:119:16)
at node.js:902:3
E: ode>node event.js
module.js:340
throw err;
^
Error: Cannot find module 'event'
at Function.Module._resolveFilename (module.js:338:15)
at Function.Module._load (module.js:280:25)
at Module.require (module.js:364:17)
at require (module.js:380:17)
at Object.<anonymous> (E:
odeevent.js:2:13)
at Module._compile (module.js:456:26)
at Object.Module._extensions..js (module.js:474:10)
at Module.load (module.js:356:32)
at Function.Module._load (module.js:312:12)
at Function.Module.runMain (module.js:497:10)
E:
ode>node event.js
listener1 arg1 参数 arg2 参数
listener2 arg1 参数 arg2 参数
E: ode>