第三章-nodejs基础知识

本章将学习nodejs基础框架,分为五个部分:nodejs的控制台事件处理机制事件环机制为事件指定事件以及取消该事件执行的回调函数nodejs中进行调试

3.1 nodejs的控制台

3.1.1 console.log方法
console.log('test console');//test console
//如果在cmd中输入 node console.js 1>info.log 会发生奇效
//转换成字符串输出,从第二个参数开始输出
console.log("%s",'two','three');//two three
console.log('%s','two',{foo:'bar'});//two {foo:'bar'} 
//将数值转换为字符串后输出,从第二个参数开始
console.log('%d',10,10.5);//10 10.5
console.log('%d','string');//NaN
console.log('%%','two');//% two
console.log(2+2);//4
console.log(2/0);//infinity
console.log("2+2");//2+2 当成字符串输出
let a=1,b=2;
console.log(a=b);//输出2 
console.log(a.toString()+b.toString())//22
3.1.2 console.error方法

用于进行标准错误输出流的输出,会向控制台输出一行错误信息。

//consoleError.js
console.error("this is error");

将错误信息保存在另外一个文件夹
node consoleError 2>error.log
如果是去node一个不存在的文件夹则会将报错信息保存在error.log里面

第三章-nodejs基础知识_第1张图片
node不存在的文件夹

3.1.3 console.dir方法

查看一个对象中的内容并输出。

let obj=new Object();
obj.name='Yuichi chiba';
obj.getName=function(){
    return this.name;
}
obj.setName=function(name){
    return this.name=name;
}
console.dir(obj)//会输出整个obj 但是getName和setName均以 [Function]代替
3.1.4 console.time和console.timeEnd方法

计算时间,里面参数必须保持一致

console.time('time go');
for(let i=0;i<100000;i++){

}
console.timeEnd('time go');
//会在控制台输出 time go:2ms (毫秒数每次不一定一样)
3.1.5 console.trace方法

用于将当前位置处的栈信息作为标准错误信息进行输出

//consoleTrace.js
let obj=new Object();
obj.name="Yuichi chiba";
obj.getName=function(){
    return this.name;
}
obj.setName=function(name){
    return this.name=name;
}
console.trace('console.trace')
第三章-nodejs基础知识_第2张图片
cmd
3.1.6 console.assert 方法

会判断第一个参数是否正确,如果不正确 第二个参数则是报错的信息

console.assert(1==2,'1不等于2');//Assertion failed: 1不等于2

3.2全局作用域 全局函数 全局对象 全局变量

3.2.1全局作用域

即可以定义一些不需要通过任何模块的加载即可使用的变量、函数或者类。同时也预先定义了一些全局方法及全局类。

console.log(global);

第三章-nodejs基础知识_第3张图片
global

3.2.2 全局函数

setTimeout可以传入三个参数setTimeout(cb,ms,[arg..])第三个参数是传给cb的函数参数
clearTimeout
setInterval可以传入三个参数setInterval(cb,ms,[arg..])第三个参数是传给cb的函数参数
clearInterval
require引入模块

3.2.3 全局对象 global
3.2.4 全局变量 process console require

process

process全局变量,即global对象的属性。用于描述当前Node.js进程状态的对象,提供一个与操作系统的简单接口。在写本地命令行程序的时候,需要用到。

process.nextTick(callback[, ...args])

方法将 callback添加到下一个时间点的队列。 在 JavaScript 堆栈上的当前操作运行完成之后以及允许事件循环继续之前,此队列会被完全耗尽。意思就是该方法发生在所有异步任务之前, 如果要递归地调用 process.nextTick(),则可以创建无限的循环。

console.log('1');
process.nextTick(testNextTick,'testNextTick');
function testNextTick(){
    console.log('console from testTextTick function');
}
setTimeout(function(){
    console.log('console from setTimeout')
})
console.log(2)
// 1
//2
// console from testTextTick function
//console from setTimeout

用法和setTimeout有一点儿相似,但是效率比setTimeout好很多。
require
require.main

//在testModule.js中
let testVar="This is a variable from testModule.js";
exports.testVar=testVar;
if(module===require.main){
    console.log('testModule.js是应用程序中主模块')
}
//在app.js中
let testModule=require('./testModule');
console.log(testModule.testVar);
if(module===require.main){
    console.log('app.js是应用程序中主模块')
}
//输出结果:
//This is a variable from testModule.js
//app.js是应用程序中主模块

如果多次引入同一个js文件则会被缓存

let testModule1=require('./testModule');
let testModule2=require('./testModule');
//输出结果:
//只会输出一次:This is a variable from testModule.js

如果想要多次运行或者调用某个模块中的代码则可以

//在testModule.js中
let testVar="This is a variable from testModule.js";
let outputTestVar=function(){
    console.log(testVar);
}
exports.testVar=testVar;
exports.outputTestVar=outputTestVar;
//在app.js中
let testModule1=require('./testModule');
let testModule2=require('./testModule');
testModule1.outputTestVar();
testModule2.outputTestVar();
//输出结果:
//This is a variable from testModule.js
//This is a variable from testModule.js

require.resolve

查询某个模块文件的带有绝对路径的文件名,但不会加载这个模块

repl环境中输入require.resolve('./testModule.js')
会输出:'/Users/kxf/Desktop/nodeJs/code/day4/testModule.js'

//app.js
let fileUrl=require.resolve('./testModule.js');
console.log(fileUrl)//'/Users/kxf/Desktop/nodeJs/code/day4/testModule.js'

console方法在第上文详细讲过,不再赘述。

第三章-nodejs基础知识_第4张图片
四个全局

3.4事件处理机制和事件环机制

js中点击一个按钮可以触发click事件,在nodeJs中许多对象也可以触发事件。针对web服务器中的http.Server对象也有,可能会触发“接收到客户端请求”,“产生连接错误”等各种事件。

3.4.1EventEmitter类

实现各类事件处理的event模块,定义了一个EventEmitter类,所有可能触发事件的对象都是一个继承了EventEmitter类的子类的实例对象。

方法名及参数 描述
addListener(event,listener) 对指定事件绑定事件处理函数
on(event,listener) addListener的别名
once(event,listener) 对指定事件只执行一次的事件处理函数
removeListener(event,listener) 对指定事件解除事件处理函数
removeAllListener([event]) 对指定事件解除所有事件处理函数
setMaxListeners(n) 指定事件处理函数的最大数量。n为整数
listeners(event) 获取指定事件的所有事件处理函数
emit(event,[arg1],[arg2],[..]) 手动触发指定事件

例子:

const EventEmitter=require('events').EventEmitter;
let myEvent1=new EventEmitter();
myEvent1.on('event',(a,b)=>{
    console.log(a+b);//3
})
myEvent1.emit('event',1,2);

也可以这样创建一个http服务

//EventEmitter.js
let http=require('http');
let server=http.createServer();
server.on('request',(req,res)=>{
    console.log(req.url);
    res.end();
})
server.listen(8888,'127.0.0.1');

运行node --inspect EventEmitter.js,然后打开node调试器。

打印结果

自定义事件触发:

//测试自定义事件并将其触发
let http=require("http");
let server=http.createServer();
server.on('request',(req,res)=>{
    if(req.url!=='/favicon.ico'){
        console.log(req.url);
    }
    res.end();
})
server.on('customEvent',(arg1,arg2)=>{
    console.log('自定义(customEvent)事件被触发');
    console.log(arg1);
    console.log(arg2);
})
server.emit('customEvent','自定义参数1','自定义参数2');
server.listen(1337,'127.0.0.1');
//自定义(customEvent)事件被触发
//自定义参数1
//自定义参数2
// /

测试newListenerremoveListener

//测试newListener和removeListener
let http=require('http');
let server=http.createServer();
server.on('newListener',function(e,f){
    console.log('对'+e+'事件添加事件处理函数');
    console.log(f)
})
server.on('removeListener',function(e,f){
    console.log('对'+e+'事件取消事件处理函数');
    console.log(f)
})
let testFunction=function(req,res){
    if(req.url!=='/favicon.ico'){
        console.log(req.url)
    }
}
server.on('request',function(req,res){
    if(req.url!=='/favicon.ico'){
        console.log(req.url)
    }
    res.end();
})
server.on('request',testFunction);
server.removeListener('request',testFunction);
server.listen(1337,'127.0.0.1');

第三章-nodejs基础知识_第5张图片
打印结果

newListener:任何时候当对继承了 EventEmitter类的子类实力对象绑定事件处理函数时,都会触发 newListener事件

3.4.2事件环机制

你可能感兴趣的:(第三章-nodejs基础知识)