码迷,mamicode.com
首页 > Web开发 > 详细

node.js Foundation

时间:2015-10-29 12:43:22      阅读:229      评论:0      收藏:0      [点我收藏+]

标签:


events 事件有两种:

System Events  C++ Core libuv   

Custom Events  JavaScript Core Event Emitter


一.The node event emitter


1.创建 Emitter module 


新建 emitte.js文件

代码如下

  1. function Emitter(){

  2. this.events = {};

  3. }

  4. // 为事件注册监听器

  5. Emitter.prototype.on = function(type,listener) {

  6. this.events[type] = this.events[type]||[];

  7. this.events[type].push(listener);

  8. };

  9. //发射,something happend, listener responed

  10. Emitter.prototype.emit = function(type){

  11. if (this.events[type]){

  12. this.events[type].forEach(function(listener){

  13. listener();

  14. })

  15. }

  16. }

  17. module.exports = Emitter;

2.引入emitter 模块

创建app.js 文件

代码如下

  1. var Emitter = require('./emitter');

  2. var emtr = new Emitter();

  3. emtr.on('greet',function(){

  4. console.log('Somewhere,some said hello.');

  5. }); //注册事件以及监听器

  6. emtr.on('greet',function(){

  7. console.log('A greet occured!');

  8. })

  9. emtr.emit('greet');



二.node.js中的events模块

使用nodejs 中的emit 


将上述app.js 改为

  1. var Emitter = require('events');

  2. var emtr = new Emitter();

  3. emtr.on('greet',function(){

  4. console.log('Somewhere,some said hello.');

  5. }); //注册事件以及监听器

  6. emtr.on('greet',function(){

  7. console.log('A greet occured!');

  8. })

  9. emtr.emit('greet');



但是以上使用string 注册事件的方式容易出错


新建config.js文件

代码如下: 

  1. module.exports = {

  2. events :{

  3. GREET:'greet',

  4. FILESAVED:'filesaved'

  5. }

  6. }


现在修改app.js文件如下:


  1. var Emitter = require('events');

  2. var eventConfig = require('./config')

  3. var emtr = new Emitter();

  4. emtr.on(eventConfig.greet,function(){

  5. console.log('Somewhere,some said hello.');

  6. }); //注册事件以及监听器

  7. emtr.on(eventConfig.greet,function(){

  8. console.log('A greet occured!');

  9. })

  10. emtr.emit(eventConfig.greet);


这样有利于代码的维护升级



三. Object.create prototypes


使用Object.create 生成object 的原型

创建 app.js ,代码如下: 


  1. var person = {

  2. firstname: '',

  3. secondname:'',

  4. greet: function(){

  5. return this.firstname+' '+this.lastname;

  6. }

  7. }

  8. var john = Object.create(person);

  9. john.firstname = 'John'

  10. john.lastname = 'Doe';

  11. var jane = Object.create(person);

  12. jane.firstname = 'Jane';

  13. jane.lastname = 'Doe';

  14. console.log(john.greet());

  15. console.log(jane.greet());


四.Inheriting from event emitter


创建 app.js,使用util模块中的 inherits 来继承原型

代码如下

  1. var EventEmitter = require('events');

  2. var util  = require('util');

  3. function Greeter(){

  4. this.greeting  = 'Hello world!';

  5. }

  6. util.inherits(Greeter,EventEmitter);

  7. Greeter.prototype.greet = function(data){

  8. console.log('Hello,this is '+data);

  9. this.emit('greet',data);

  10. }

  11. var greeter = new Greeter();

  12. greeter.on('greet',function(data){

  13. console.log('Hello ,this is an events : '+data);

  14. });

  15. greeter.greet('Tony');


五.ECMAScript 6

literal strings

  1. var name = 'Nike';

  2. var greet = `Hello ${name}`;

  3. console.log(greet);

call and apply

用于改变调用者 this

  1. var obj = {

  2. name:'John Doe',

  3. greet: function(){

  4. console.log(this.name);

  5. }

  6. }

  7. obj.greet.call({name : 'Jane Doe'});

  8. obj.greet.apply({name: 'Jane Doe'});



  1. var util = require('util');

  2. function Person(){

  3. this.firstname = 'John';

  4. this.lastname = 'Doe';

  5. }

  6. Person.prototype.greet = function (){

  7. console.log('Hello '+this.firstname + ' '+ this.lastname);

  8. }

  9. function Policeman(){

  10. Person.call(this);//very important

  11. this.badgenumber = '1234';

  12. }

  13. util.inherits(Policeman,Person);

  14. var pol=  new Policeman();

  15. 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的使用:

  1. var buf  = new Buffer('Hello','utf8');

  2. console.log(buf);

  3. console.log(buf.toString());

  4. console.log(buf.toJSON());

  5. console.log(buf[2]);

  6. buf.write('wo');

  7. 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



  1. var fs = require('fs');

  2. var greet = fs.readFileSync(__dirname+'/greet.txt','utf8');

  3. console.log(greet);

  4. var greet2 = fs.readFile(__dirname+'/greet.txt',function(err,data){

  5. console.log(data.toString());

  6. });

  7. console.log('Done');



things about createWriteStream createReadStream 


  1. var fs = require('fs');

  2. var readable = fs.createReadStream(__dirname+'/greet.txt',{encoding: 'utf8',highWaterMark: 16*1024});

  3. var writable = fs.createWriteStream(__dirname + '/greatcopy.txt');

  4. readable.on('data',function(chunk){

  5. console.log(chunk.length);

  6. writable.write(chunk);

  7. });


pipe 

技术分享


  1. var fs = require('fs');

  2. var zlib = require('zlib');

  3. var readable = fs.createReadStream(__dirname+'/greet.txt' );

  4. var writable = fs.createWriteStream(__dirname + '/greatcopy.txt');

  5. var compressed = fs.createWriteStream(__dirname + '/great.txt.gz');

  6. var gzip = zlib.createGzip();

  7. readable.pipe(writable);

  8. readable.pipe(gzip).pipe(compressed);


技术分享




HTTP_PARSER


  1. var  http = require('http');

  2. http.createServer(function(req,res){

  3. res.writeHead(200,{'Content-Type':'text/plain'})

  4. res.end('Hello world\n');

  5. }).listen(1337,'127.0.0.1');


 引入html 文件


  1. var  http = require('http');

  2. var fs = require('fs');

  3. http.createServer(function(req,res){

  4. res.writeHead(200,{'Content-Type':'text/html'});

  5. var html = fs.readFileSync(__dirname+'/index.html');

  6. res.end(html);

  7. }).listen(1337,'127.0.0.1');


  1. var  http = require('http');

  2. var  fs = require('fs');

  3. http.createServer(function(req,res){

  4. res.writeHead(200,{'Content-Type':'text/html'});

  5. var html = fs.createReadStream(__dirname+'/index.html').pipe(res)

  6. }).listen(1337,'127.0.0.1');




OutPut  JSON

JSON.stringify(obj)

  1. var  http = require('http');

  2. var  fs = require('fs');

  3. http.createServer(function(req,res){

  4. res.writeHead(200,{'Content-Type':'application/json'});

  5. var obj = {

  6. firstname:'John',

  7. lastname:'Doe'

  8. };

  9. res.end(JSON.stringify(obj));

  10. }).listen(1337,'127.0.0.1');

Routing: 

mapping  http requests to  contents



  1. var  http = require('http');

  2. var  fs = require('fs');

  3. http.createServer(function(req,res){

  4. if(req.url === '/'){

  5. fs.createReadStream(__dirname+'/index.html').pipe(res);

  6. }

  7. if(res.url === '/api'){

  8. res.writeHead(200,{'Content-Type':'application/json'});

  9. var obj = {

  10. firstname:'John',

  11. lastname:'Doe'

  12. };

  13. res.end(JSON.stringify(obj));

  14. }

  15. res.writeHead(404);

  16. res.end();

  17. }).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



使用别人的代码




  1. var express = require('express');

  2. var app = express();

  3. var port = process.env.PORT || 3000;

  4. app.use('/assets',express.static(__dirname+'/public'));

  5. app.use('/',function(req,res,next){

  6. console.log('Request Url: ' + req.url);

  7. next();

  8. })

  9. app.get('/',function(req,res){

  10. res.send('<html><head><link href = assets/style.css type =text/css rel = stylesheet /></head><body><h1>Hello world</h1></body></html>');

  11. });

  12. app.get('/person/:id',function(req,res){

  13. res.send('<html><body><h1> Person: '+req.params.id+'</h1></body></html>');

  14. })

  15. app.get('/api',function(req,res){

  16. res.send('<html><body><h1>Hello world</h1></body></html>')

  17. })

  18. app.listen(port);



  1. var express = require('express');

  2. var app = express();

  3. var port = process.env.PORT || 3000;

  4. app.use('/assets',express.static(__dirname+'/public'));

  5. app.set('view engine','ejs')

  6. app.use('/',function(req,res,next){

  7. console.log('Request Url: ' + req.url);

  8. next();

  9. })

  10. app.get('/person/:id',function(req,res){

  11. res.render('person',{ID: req.params.id,QStr: req.query.qstr});

  12. })

  13. app.listen(port);

person.ejs:


  1. <html>

  2. <head>

  3. <link href ='assets/styl.css' type = "text/css" ref= "stylesheeet" />

  4. </head>

  5. <body>

  6. <h1>Peson: <%=ID %> </h1>

  7. <h2>Query String Value: <%= QStr %> </h2>

  8. </body>

  9. </html>



npm install body-parser



  1. var express = require('express');

  2. var bodyParser = require('body-parser');

  3. var app = express();

  4. var urlencodedParser = bodyParser.urlencoded({extended: false});

  5. var jsonParser = bodyParser.json();

  6. var port = process.env.PORT || 3000;

  7. app.use('/assets',express.static(__dirname+'/public'));

  8. app.set('view engine','ejs')

  9. app.get('/',function(req,res){

  10. res.render('index');

  11. })

  12. app.get('/person/:id',function(req,res){

  13. res.render('person',{ID: req.params.id,QStr: req.query.qstr});

  14. })

  15. app.post('/person',urlencodedParser,function(req,res){

  16. res.send('Thank You!');

  17. console.log(req.body.firstname);

  18. console.log(req.body.lastname);

  19. })

  20. app.post('/personjson',jsonParser,function(req,res){

  21. res.send('Thank you jsonParser');

  22. console.log(req.body.firstname);

  23. console.log(req.body.lastname);

  24. })

  25. app.listen(port);


index.ejs

  1. <html>

  2. <head>

  3. <link href ='/assets/styl.css' type = "text/css" ref= "stylesheeet" />

  4.    <script src = "http://ajax.aspnetcdn.com/ajax/jQuery/jquery-2.1.4.min.js"></script>

  5. </head>

  6. <body>

  7. <h1>Hello World!</h1>

  8. <form method ='POST' action="/person">

  9. First name: <input type ="text" id ="firstname" name ="firstname"/><br>

  10. Last  name: <input type ="text" id= "lastname" name= "lastname"/><br>

  11. <input type ="submit" value ="submit"/>

  12. </form>

  13. <script>

  14. $.ajax({

  15. type: "POST",

  16. url: "/personjson",

  17. data: JSON.stringify({firstname: "John",lastname:"Doe"}),

  18. dataType: 'json',

  19. contentType: 'application/json'

  20. })

  21. </script>

  22. </body>

  23. </html>


mongoose











node.js Foundation

标签:

原文地址:http://www.cnblogs.com/lifreesh/p/4919730.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!