events 事件有两种:
System Events C++ Core libuv
Custom Events JavaScript Core Event Emitter
一.The node event emitter
1.创建 Emitter module
新建 emitte.js文件
代码如下
function Emitter(){
this.events = {};
}
// 为事件注册监听器
Emitter.prototype.on = function(type,listener) {
this.events[type] = this.events[type]||[];
this.events[type].push(listener);
};
//发射,something happend, listener responed
Emitter.prototype.emit = function(type){
if (this.events[type]){
this.events[type].forEach(function(listener){
listener();
})
}
}
module.exports = Emitter;
2.引入emitter 模块
创建app.js 文件
代码如下
var Emitter = require('./emitter');
var emtr = new Emitter();
emtr.on('greet',function(){
console.log('Somewhere,some said hello.');
}); //注册事件以及监听器
emtr.on('greet',function(){
console.log('A greet occured!');
})
emtr.emit('greet');
二.node.js中的events模块
使用nodejs 中的emit
将上述app.js 改为
var Emitter = require('events');
var emtr = new Emitter();
emtr.on('greet',function(){
console.log('Somewhere,some said hello.');
}); //注册事件以及监听器
emtr.on('greet',function(){
console.log('A greet occured!');
})
emtr.emit('greet');
但是以上使用string 注册事件的方式容易出错
新建config.js文件
代码如下:
module.exports = {
events :{
GREET:'greet',
FILESAVED:'filesaved'
}
}
现在修改app.js文件如下:
var Emitter = require('events');
var eventConfig = require('./config')
var emtr = new Emitter();
emtr.on(eventConfig.greet,function(){
console.log('Somewhere,some said hello.');
}); //注册事件以及监听器
emtr.on(eventConfig.greet,function(){
console.log('A greet occured!');
})
emtr.emit(eventConfig.greet);
这样有利于代码的维护升级
三. Object.create prototypes
使用Object.create 生成object 的原型
创建 app.js ,代码如下:
var person = {
firstname: '',
secondname:'',
greet: function(){
return this.firstname+' '+this.lastname;
}
}
var john = Object.create(person);
john.firstname = 'John'
john.lastname = 'Doe';
var jane = Object.create(person);
jane.firstname = 'Jane';
jane.lastname = 'Doe';
console.log(john.greet());
console.log(jane.greet());
四.Inheriting from event emitter
创建 app.js,使用util模块中的 inherits 来继承原型
代码如下
var EventEmitter = require('events');
var util = require('util');
function Greeter(){
this.greeting = 'Hello world!';
}
util.inherits(Greeter,EventEmitter);
Greeter.prototype.greet = function(data){
console.log('Hello,this is '+data);
this.emit('greet',data);
}
var greeter = new Greeter();
greeter.on('greet',function(data){
console.log('Hello ,this is an events : '+data);
});
greeter.greet('Tony');
五.ECMAScript 6
literal strings
var name = 'Nike';
var greet = `Hello ${name}`;
console.log(greet);
call and apply
用于改变调用者 this
var obj = {
name:'John Doe',
greet: function(){
console.log(this.name);
}
}
obj.greet.call({name : 'Jane Doe'});
obj.greet.apply({name: 'Jane Doe'});
var util = require('util');
function Person(){
this.firstname = 'John';
this.lastname = 'Doe';
}
Person.prototype.greet = function (){
console.log('Hello '+this.firstname + ' '+ this.lastname);
}
function Policeman(){
Person.call(this);//very important
this.badgenumber = '1234';
}
util.inherits(Policeman,Person);
var pol= new Policeman();
pol.greet();
Javascript 同步的
Nodejs 异步的
Event Driven No-Blocking I?O in V* javascript
no-blocking : do other things without stopping your programing from running
Buffer
the relationship between buffer and stream
缓冲区 Buffer的使用:
var buf = new Buffer('Hello','utf8');
console.log(buf);
console.log(buf.toString());
console.log(buf.toJSON());
console.log(buf[2]);
buf.write('wo');
console.log(buf.toString()); //wollo, 会覆盖缓冲区
Files and fs
ERROR_FIRST CALLBACK:
callbacks takes an error object as the first parameters;
CHUNK:
A piece of data sent through a stream
Data is split in 'chunks' and streamed
var fs = require('fs');
var greet = fs.readFileSync(__dirname+'/greet.txt','utf8');
console.log(greet);
var greet2 = fs.readFile(__dirname+'/greet.txt',function(err,data){
console.log(data.toString());
});
console.log('Done');
things about createWriteStream createReadStream
var fs = require('fs');
var readable = fs.createReadStream(__dirname+'/greet.txt',{encoding: 'utf8',highWaterMark: 16*1024});
var writable = fs.createWriteStream(__dirname + '/greatcopy.txt');
readable.on('data',function(chunk){
console.log(chunk.length);
writable.write(chunk);
});
pipe
var fs = require('fs');
var zlib = require('zlib');
var readable = fs.createReadStream(__dirname+'/greet.txt' );
var writable = fs.createWriteStream(__dirname + '/greatcopy.txt');
var compressed = fs.createWriteStream(__dirname + '/great.txt.gz');
var gzip = zlib.createGzip();
readable.pipe(writable);
readable.pipe(gzip).pipe(compressed);
HTTP_PARSER
var http = require('http');
http.createServer(function(req,res){
res.writeHead(200,{'Content-Type':'text/plain'})
res.end('Hello world\n');
}).listen(1337,'127.0.0.1');
引入html 文件
var http = require('http');
var fs = require('fs');
http.createServer(function(req,res){
res.writeHead(200,{'Content-Type':'text/html'});
var html = fs.readFileSync(__dirname+'/index.html');
res.end(html);
}).listen(1337,'127.0.0.1');
var http = require('http');
var fs = require('fs');
http.createServer(function(req,res){
res.writeHead(200,{'Content-Type':'text/html'});
var html = fs.createReadStream(__dirname+'/index.html').pipe(res)
}).listen(1337,'127.0.0.1');
OutPut JSON
JSON.stringify(obj)
var http = require('http');
var fs = require('fs');
http.createServer(function(req,res){
res.writeHead(200,{'Content-Type':'application/json'});
var obj = {
firstname:'John',
lastname:'Doe'
};
res.end(JSON.stringify(obj));
}).listen(1337,'127.0.0.1');
Routing:
mapping http requests to contents
var http = require('http');
var fs = require('fs');
http.createServer(function(req,res){
if(req.url === '/'){
fs.createReadStream(__dirname+'/index.html').pipe(res);
}
if(res.url === '/api'){
res.writeHead(200,{'Content-Type':'application/json'});
var obj = {
firstname:'John',
lastname:'Doe'
};
res.end(JSON.stringify(obj));
}
res.writeHead(404);
res.end();
}).listen(1337,'127.0.0.1');
使用 npm
进入文件夹
npm init ;
npm install moment
发布文件后,删除node_modules后,
使用npm install
--save 添加到package.json 文件中
npm install jasmine-node --save-dev 开发依赖模块
npm install -g nodemon 全局安装
npm update ,更新所有的dependencies
使用别人的代码
var express = require('express');
var app = express();
var port = process.env.PORT || 3000;
app.use('/assets',express.static(__dirname+'/public'));
app.use('/',function(req,res,next){
console.log('Request Url: ' + req.url);
next();
})
app.get('/',function(req,res){
res.send('<html><head><link href = assets/style.css type =text/css rel = stylesheet /></head><body><h1>Hello world</h1></body></html>');
});
app.get('/person/:id',function(req,res){
res.send('<html><body><h1> Person: '+req.params.id+'</h1></body></html>');
})
app.get('/api',function(req,res){
res.send('<html><body><h1>Hello world</h1></body></html>')
})
app.listen(port);
var express = require('express');
var app = express();
var port = process.env.PORT || 3000;
app.use('/assets',express.static(__dirname+'/public'));
app.set('view engine','ejs')
app.use('/',function(req,res,next){
console.log('Request Url: ' + req.url);
next();
})
app.get('/person/:id',function(req,res){
res.render('person',{ID: req.params.id,QStr: req.query.qstr});
})
app.listen(port);
person.ejs:
<html>
<head>
<link href ='assets/styl.css' type = "text/css" ref= "stylesheeet" />
</head>
<body>
<h1>Peson: <%=ID %> </h1>
<h2>Query String Value: <%= QStr %> </h2>
</body>
</html>
npm install body-parser
var express = require('express');
var bodyParser = require('body-parser');
var app = express();
var urlencodedParser = bodyParser.urlencoded({extended: false});
var jsonParser = bodyParser.json();
var port = process.env.PORT || 3000;
app.use('/assets',express.static(__dirname+'/public'));
app.set('view engine','ejs')
app.get('/',function(req,res){
res.render('index');
})
app.get('/person/:id',function(req,res){
res.render('person',{ID: req.params.id,QStr: req.query.qstr});
})
app.post('/person',urlencodedParser,function(req,res){
res.send('Thank You!');
console.log(req.body.firstname);
console.log(req.body.lastname);
})
app.post('/personjson',jsonParser,function(req,res){
res.send('Thank you jsonParser');
console.log(req.body.firstname);
console.log(req.body.lastname);
})
app.listen(port);
index.ejs
<html>
<head>
<link href ='/assets/styl.css' type = "text/css" ref= "stylesheeet" />
<script src = "http://ajax.aspnetcdn.com/ajax/jQuery/jquery-2.1.4.min.js"></script>
</head>
<body>
<h1>Hello World!</h1>
<form method ='POST' action="/person">
First name: <input type ="text" id ="firstname" name ="firstname"/><br>
Last name: <input type ="text" id= "lastname" name= "lastname"/><br>
<input type ="submit" value ="submit"/>
</form>
<script>
$.ajax({
type: "POST",
url: "/personjson",
data: JSON.stringify({firstname: "John",lastname:"Doe"}),
dataType: 'json',
contentType: 'application/json'
})
</script>
</body>
</html>
mongoose