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. curl_get和curl_post,伪造请求头,绕过防盗链下载文件

    //curl-get function curl_get($url, $timeout = 10) { $ch = curl_init();//初始化 curl_setopt($ch, CURLOPT ...

  2. BZOJ 4003: [JLOI2015]城池攻占 左偏树 可并堆

    https://www.lydsy.com/JudgeOnline/problem.php?id=4003 感觉就是……普通的堆啊(暴论),因为这个堆是通过递归往右堆里加一个新堆或者新节点的,所以要始 ...

  3. 2、Redis的基础知识

     写在前面的话:读书破万卷,编码如有神 -------------------------------------------------------------------- 主要内容包括: red ...

  4. Codeforces Round #358 (Div. 2) B. Alyona and Mex 水题

    B. Alyona and Mex 题目连接: http://www.codeforces.com/contest/682/problem/B Description Someone gave Aly ...

  5. 自动化运维工具 ~puppet~

    一.模板的应用 到目前为止,资源申报.定义类.声明类等所有功能都只能一个manifest文件中实现,但这却非有效的基于puppet管理IT资源架构的方式.实践 中,一般需要把manifest文件分解成 ...

  6. SPOJ 3267. D-query (主席树,查询区间有多少个不相同的数)

    3267. D-query Problem code: DQUERY English Vietnamese Given a sequence of n numbers a1, a2, ..., an  ...

  7. Memcached (第一篇)

    Memcached是“分布式”的内存对象缓存系统,那么不需要“分布”的.不需要共享的或者干脆规模小到只有一台服务器的应用,Memcached不会带来任何好处,相反还会拖慢系统效率,因为网络连接同样需要 ...

  8. C++空类产生哪些成员函数 || C++类可以自动生成的6个成员函数

    class Empty {     public:     Empty(); // 缺省构造函数     Empty( const Empty& ); // 拷贝构造函数     ~Empty ...

  9. 【spring cloud】【docker】使用docker在centOS上部署spring cloud微服务架构服务

    项目GitHub地址 ================================================================================== 部署过程: ...

  10. 【centOS7】centOS7上普通用户切换root用户,相互切换

    当前普通用户登录,想要切换为root用户,需要输入命令 su 需要输入root密码.输入时候屏幕不会显示,直接输入完了,回车即可 回车后,即切换到root用户下 想要从root用户切换到普通用户,只需 ...