Chat Emitter

We're going to create a custom chat EventEmitter.

Create a new EventEmitter object and assign it to a variable called 'chat'.

var chat = new EventEmitter();

Next, let's listen for the 'message' event on our new chat object. Remember to add a callback that accepts the message parameter.

chat.on('message', function(message){

});

Log the message to the console using console.log().

chat.on('message', function(message){
console.log(message);
});
var events = require('events');
var EventEmitter = events.EventEmitter; var chat = new EventEmitter();
chat.on('message', function(message){
console.log(message);
});

Emitting Events

Read the existing code below and modify it to emit events.

On the chat object, emit the 'join' event and pass in a custom message as a string.

// Emit events here
chat.emit('join', "Hello");

Now emit the 'message' event on the chat object. Just like before, remember to pass in a custom message as a string.

chat.emit('message', "Message: ");
var events = require('events');
var EventEmitter = events.EventEmitter; var chat = new EventEmitter();
var users = [], chatlog = []; chat.on('message', function(message) {
chatlog.push(message);
}); chat.on('join', function(nickname) {
users.push(nickname);
}); // Emit events here
chat.emit('join', "Hello");
chat.emit('message', "Message: ");

Request Event

Just like you saw in the video, refactor the HTTP server code to explicitly bind a callback to the 'request' event using the onfunction.

Add an event listener on the server variable that listens to the requestevent. The event listener should take a callback function with two arguments, request and response.

server.on('request', function(request, response){});

Move the logic for handling the request from the http.createServer()callback to your new 'request' event listener. Remember to remove thehttp.createServer() callback once the code has been moved.

var server = http.createServer(function(request, response){
response.writeHead(200);
response.write("Hello, this is dog");
response.end();
}); //change to
var server = http.createServer();
server.on('request', function(request, response){
response.writeHead(200);
response.write("Hello, this is dog");
response.end();
});

Listening Twice

Who said you can only listen for an event once?

Add a second 'request' handler to the HTTP server.

server.on('request', function(request, response){});

From inside of the new handler, log the message "New request coming in..." using console.log().

var http = require('http');
var server = http.createServer(); server.on('request', function(request, response){
response.writeHead(200);
response.write("Hello, this is dog");
response.end();
}); server.on('request', function(request, response){
console.log("New request coming in...");
}); server.listen(8080);

Listening for Close

Like our parents always used to say, listening is more important than talking! Modify the server so that we know when it's closed down.

Listen for the 'close' event on the server. The event listener should take a callback function that accepts no arguments.

server.on('close', function(){});

Inside the 'close' callback, log the message "Closing down the server...".

server.on('close', function(){
console.log("Closing down the server...");
});
var http = require('http');
var server = http.createServer(); server.on('request', function(request, response) {
response.writeHead(200);
response.write("Hello, this is dog");
response.end();
}); server.on('request', function(request, response) {
console.log("New request coming in...");
}); server.on('close', function(){
console.log("Closing down the server...");
}); server.listen(8080);

[Node.js] Level 2 new. Event的更多相关文章

  1. Node.js 事件循环(Event Loop)介绍

    Node.js 事件循环(Event Loop)介绍 JavaScript是一种单线程运行但又绝不会阻塞的语言,其实现非阻塞的关键是“事件循环”和“回调机制”.Node.js在JavaScript的基 ...

  2. [Node.js] Level 7. Persisting Data

    Simple Redis Commands Let's start practicing using the redis key-value store from our node applicati ...

  3. [Node.js] Level 6. Socket.io

    6.2 Setting Up socket.io Server-Side So far we've created an Express server. Now we want to start bu ...

  4. [Node.js] Level 3 new. Steam

    File Read Stream Lets use the fs module to read a file and log its contents to the console. Use the  ...

  5. [Node.js] Level 5. Express

    Express Routes Let's create an express route that accepts GET requests on'/tweets' and responds by s ...

  6. 浅析Node.js的Event Loop

    目录 浅析Node.js的Event Loop 引出问题 Node.js的基本架构 Libuv Event Loop Event Loop Phases Overview Poll Phase The ...

  7. Node.js Event Loop 的理解 Timers,process.nextTick()

    写这篇文章的目的是将自己对该文章的理解做一个记录,官方文档链接The Node.js Event Loop, Timers, and process.nextTick() 文章内容可能有错误理解的地方 ...

  8. Node.js Web 开发框架大全《中间件篇》

    这篇文章与大家分享优秀的 Node.js 中间件模块.Node 是一个服务器端 JavaScript 解释器,它将改变服务器应该如何工作的概念.它的目标是帮助程序员构建高度可伸缩的应用程序,编写能够处 ...

  9. Node.js异步处理CPU密集型任务

    Node.js异步处理CPU密集型任务 Node.js擅长数据密集型实时(data-intensive real-time)交互的应用场景.然而数据密集型实时应用程序并非仅仅有I/O密集型任务,当碰到 ...

随机推荐

  1. bzoj 1312 最大密度子图

    晕,m=0是要输出1(弄的我还找管理员要数据,但明显题意是叫我们输出0呀) 最大密度子图,把边转换成点,然后二分答案,跑最大权闭合子图判定是否可行. #include <cstdio> # ...

  2. bzoj 4322 东西分配问题

    问题:有n个东西,分给m个人,对于每个东西,每个人有喜欢与不喜欢两种态度:like[i][j],如果喜欢,那么他得到该东西时增加的喜悦度为k,否则为1,问是否存在一种分法,使得每个人都达到该人的最低喜 ...

  3. bzoj 4017 子序列和的异或以及异或的和

    位运算很好的一个性质是可以单独每一位考虑..... 题解请看:http://blog.csdn.net/skywalkert/article/details/45401245 对于异或的和,先枚举位, ...

  4. sql中如何统计一字段中字符串的个数

    declare @s varchar(100)set @s='156434A27kAsdABCiosd-01&**('--找出现的次数select len(@s)-len(replace(@s ...

  5. nginx新建nginx_fzjh.conf文件,不使用默认配置文件

    worker_processes 4; events{ worker_connections 1024; } http{ server { listen 80; server_name myserve ...

  6. weblogic部署异常: cvc-enumeration-valid: string value '3.0' is not a valid enumeration value for web-app-versionType in namespace http://java.sun.com/xml/ns/javaee:<null>

    尝试使用weblogic部署一个Demo应用,在选择应用目录后,报出下面的异常: VALIDATION PROBLEMS WERE FOUND problem: cvc-enumeration-val ...

  7. ESB的几个基本概念

    京-星之泪:  请教一个问题:esb中路由和管道对的概念应该怎么理解,各自有什么用途,他们之间的关系 北京-kimmking: transport  endpoint inbound  outboun ...

  8. sublime插件汇总

    JsFormat javascript格式化 有时从网上扒了人家的js代码来学习学习,打开发现被压缩了,这时就能够用JsFormat插件格式化js代码,恢复未压缩时候的排版,挺给力的.按快捷键Ctrl ...

  9. linux内核源码之基础准备篇

    http://blog.csdn.net/eastmoon502136/article/details/8711104

  10. 怎样在MyEclipse上耍Chrome

    近期在忙着期末大作业,所以Windows App和算法的专栏都没有更了,随后这几天都会陆续開始更新的,欢迎大家的关注啦-- 在写期末大作业的时候遇到一个问题.一个新的特性在MyEclipse自带的浏览 ...