node.js Foundation

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

来自为知笔记(Wiz)

时间: 2024-10-13 11:11:45

node.js Foundation的相关文章

Node.js 学习资源

这篇文章编译整理自Stack Overflow的一个如何开始学习Node.js的Wiki帖,这份资源列表在SO上面浏览接近60万次,数千个收藏和顶.特意整理发布到这里,其中添加了部分中文参考资料. 学习指南和教程 NodeSchool.io 交互式课程 Node的艺术 (Node简介) Hello World Hello World Web Server Node.js 指南 使用Node.js, express和MongoDB创建一个博客 Node+MongoDB 100分钟建站攻略 Proj

(翻译)《Hands-on Node.js》—— 引言

今天开始会和大熊君{{bb}}一起着手翻译node的系列外文书籍,大熊负责翻译<Node.js IN ACTION>一书,而我暂时负责翻译这本<Hands-on Node.js>(下载),为方便理解不采用直译的方式,若有翻译不当的地方还请不吝赐教,我会及时堪正. 引言 在09年欧洲JSConf大会上,一位叫做Ryan Dahl的年轻程序员介绍了一项他所负责的项目.该项目结合了谷歌V8 Javascript引擎以及event loop机制,从而可以使用JS来创建服务端平台.该项目跟其

Node.js的学习资源、教程和工具

这篇文章编译整理自Stack Overflow的一个如何开始学习Node.js的Wiki帖,这份资源列表在SO上面浏览接近60万次,数千个收藏和顶.特意整理发布到这里,其中添加了部分中文参考资料. 学习指南和教程 NodeSchool.io 交互式课程 Node的艺术 (Node简介) Hello World Hello World Web Server Node.js 指南 使用Node.js, express和MongoDB创建一个博客 Node+MongoDB 100分钟建站攻略 Proj

node.js的安装及配置

一.安装 直接在浏览器搜索node.js,在官网上下载(一般旧版的更加稳定,比如下载4.4.7版本) 点击DOWNLOADS 往下翻,点击Previous Release Windows下载msi(64位/32位) 根据提示一步步安装,安装之后的文件夹如下: 在cmd命令行下输入node -v,如果出现如下,说明安装成功: 二.关于配置 在安装路径下新建两个文件夹: 创建完两个空文件夹之后,打开cmd命令窗口,输入 npm config set prefix "D:\Program Files

Node.js: Extend and Maintain Applications + large scale

https://blog.risingstack.com/node-js-mysql-example-handling-hundred-gigabytes-of-data/ My secondary goal with this article is to help you decide if Node.js + MySQL is a good fit for your needs, and to provide help with implementing such a solution. h

1.node.js windows环境搭建

作为服务端运行javascript的平台的NodeJs,把前台javascript移到了服务器端,Google V8引擎使其运行效率非常高,它可以异步,无任何阻塞运行程序.nodejs包含http服务器,可以为我们实现 web系统设计,客户端javascript编译器,等一系列的功能. 工具/原料 windows系统电脑 ,电脑可以上网 方法/步骤 下载windows平台nodejs环境安装包,百度一下nodejs官网,找到DOWNLOADS点击,找到Windows Installer 如果为6

在Node.js中使用RabbitMQ系列二 任务队列

在上一篇文章在Node.js中使用RabbitMQ系列一 Hello world我有使用一个任务队列,不过当时的场景是将消息发送给一个消费者,本篇文章我将讨论有多个消费者的场景. 其实,任务队列最核心解决的问题是避免立即处理那些耗时的任务,也就是避免请求-响应的这种同步模式.取而代之的是我们通过调度算法,让这些耗时的任务之后再执行,也就是采用异步的模式.我们需要将一条消息封装成一个任务,并且将它添加到任务队列里面.后台会运行多个工作进程(worker process),通过调度算法,将队列里的任

node.js搭建代理服务器请求数据

1.引入node.js中的模块 1 var http = require("http"); 2 var url = require("url"); 3 var qs = require("querystring"); 2.创建服务器 //用node中的http创建服务器 并传入两个形参 http.createServer(function(req , res) { //设置请求头 允许所有域名访问 解决跨域 res.setHeader("

Node.JS 文件读写,把Sheet图集转换为龙骨动画图集

Node.JS 文件读写,把Sheet图集数据转换为龙骨动画图集数据 var fs = require("fs") var readline = require("readline"); var rl = readline.createInterface({ input:process.stdin, output:process.stdout }); var path = undefined; var dbName = undefined; rl.question(