nodejs概念:
让javascript运行在服务端的开发平台。不是一种语言,不是框架,不是库。特点:单线程异步、事件驱动。
PHP、JAVA既是语言也是平台。
创始人:Ryan
nodejs cmd 命令:
node -v //查看nodejs版本
node -e "console.log('ok')" //eval解析javascript语言
node 回车 //进入编译模式
npm list //查看目录下安装包
npm install -g 包名 //安装全局包
nodejs 创建http服务器:
var http=require('http') http.createServer(function(req,res){ res.writeHead(200,{'Content-Type':'text/html'}); res.write('<h1>Node.js</h1>'); res.end('<p>Pcat</p>'); }).listen(3000); console.log('HTTP server is listening at port 3000');
nodejs 工具安装:
npm install -supervisor -g //全局安装supervisor
nodejs 文件读取:
异步读取:
var fs=require('fs'); fs.readFile('file.txt','UTF-8',function(err,data){ if(err){ console.log('read file err'); }else{ console.log(data) } })
console.log('end');
同步读取:
var fs=require('fs'); var data=fs.readFileSync('file.txt','UTF-8'); console.log(data); console.log('end');
nodejs 事件:
//声明事件对象 var EventEmitter=require('events').EventEmitter; var event=new EventEmitter(); //注册事件 event.on('some_event',function(){ console.log('这是一个自定义事件') }) //触发事件 setTimeout(function(){ event.emit('some_event'); },3000)
nodejs事件循环机制,所有逻辑都是事件的回调函数。
模块:
js文件,使用exports暴露公开接口,通过require函数引入模块,返回一个对象。文件可能是javascript代码、JSON或者编译过的C/C++扩展。
module.js
var name; exports.setName=function(thyName){ name=thyName; } exports.sayHello=function(){ console.log('hello '+name); }
getModule.js
var myModule=require('./module'); myModule.setName('marico'); myModule.sayHello();
问题:调用多次会如何输出?
var myModule1=require('./module'); myModule1.setName('marico'); var myModule2=require('./module'); myModule2.setName('kathra'); myModule1.sayHello();
结果为:kathra
问题:如何做到多次调用?
module.js
function hello(){ var name; this.setName=function(thyName){ name=thyName; } this.sayHello=function(){ console.log('hello '+name); } } //exports.hello=hello; module.exports=hello;
getModule.js
//var hello=require('./module').hello; var hello=require('./module'); var he=new hello(); he.setName('marico'); he.sayHello(); var he2=new hello(); he2.setName('kathra'); he2.sayHello();
包:
模块基础上更深一步的抽象,CommonJS规范的包应该具有以下特征:
1.package.json必须在包的顶层目录下
2.二进制文件应该在bin目录下
3.javascript代码应该在lib目录下
4.文档应该在doc目录下
5.单元测试应该在test目录下
nodejs对包要求并没有那么严格,只要顶层目录下有package.json,并符合基本规范即可。
nodejs在调用某个包时,会检查包中package.json文件的main字段,将其作为包的接口模块,如果package.json或main字段不存在,会尝试寻找index.js或index.code作为包的接口。
package.json的规范属性:
name:包的名称,必须唯一
description:包的简要说明
version:版本
keywords:关键字
maintainers:维护者数组,每个元素要包含name、email、web可选字段
contributors:贡献者数组,格式同maintainers,第一个为包作者
bugs:提交bug的地址,可以是网址或者电子邮件地址
licenses:许可证数组,每个元素要包含type和url字段
repositories:仓库托管地址数组,每个元素要包含type、url和path字段
dependencies:包的依赖,一个关联数组,由包名称和版本号组成