search
HomeWeb Front-endJS TutorialDetailed explanation of HTTP module and event module in Node.js_node.js

Node.js http server

Node.js allows us to create servers and clients by using the low-level API of the HTTP module. When we first started learning node, we would all encounter the following code:

Copy code The code is as follows:

var http = require('http');
http.createServer(function (req,res) {
res.end('Hello Worldn');
}).listen(3000,"127.0.0.1");
console.log("Server funning at http://127.0.0.1:3000");

This code includes information about the http module, which means:

1. Request the HTTP module from the core of `Node.js` and assign it to a variable for use in future scripts.
The script then has access to methods for using `HTTP` through `Node.js`.

2. Use `createServer` to create a new web server object

3. The script passes an anonymous function to the server, telling the web server object what to happen whenever it receives a request

4. Line 4 of the script defines the port and host of the web server, which means you can use `http://127.0.0.1:3000`
to access the server

Http header

For every HTTP request and response, an HTTP header is sent. The HTTP header sends additional information, including the content type, the date the server sent the response, and the HTTP status code

The http header contains a lot of information. The following is the http header information contained in my Baidu homepage:

Since I have added more websites to my Baidu homepage, the data here may be different from that of readers. From this we can see that Baidu’s web server is BWS/1.1

The following is the http header information of the above code:

Redirects in Node.js

In node, we can easily create a simple server to redirect visitors to another web page. The guidelines are as follows:

1. Send a 301 response code to the customer to tell the customer that the resource has been moved to another location;
2. Send a location header to tell the client where to redirect.

The relevant code is as follows:

Copy code The code is as follows:

var http = require('http');
http.createServer(function (req,res) {
res.writeHead(301,{
         'Location':'Http://example-2.com/web'
});
res.end();
}).listen(3000,'127.0.0.1');
console.log("Server funning at http://127.0.0.1:3000");

Open the browser and visit http://127.0.0.1:3000The page will be redirected.

Respond to different requests

Node.js can not only create a single response, but for multiple types of requests, we need to add some routes to the application. Node makes this straightforward by using the URL module. The URL module allows us to read a URL, parse it and then do something with the output.

Copy code The code is as follows:

var url = require('url');
var requestURL = "http://example.com:1234/path?query=string#hash"

Now we can analyze the requested URL and extract content from it, for example, to get the hostname we can type:

Copy code The code is as follows:

url.parse(requestURL).hostname

At this time, he will return to "example.com"

To obtain the port number, you can enter:

Copy code The code is as follows:

url.parse(requestURL).port

He will return "1234"

Event Module

Node.js is considered the best way to achieve concurrency. The Events module is the core of Node.js and is used by many other modules to architect functionality around events. Since Node.js runs in a single thread, any synchronization code is blocking. Therefore, we need to consider some simple rules when writing Node.js code:

1. Don’t block - `Node.js` is single-threaded, if the code blocks everything else stops
2. Quick Return – Operations should return quickly. If it cannot return quickly, it should be moved to another process
The Events module allows developers to set up listeners and handlers for events. In client js, we can set a listener for the click event and then do something when the event occurs:

Copy code The code is as follows:

var tar = document.getElementById("target");
tar.addEventListener("click", function () {
alert("click event fired,target was clicked");
},false);

Of course, this is an example without considering IE compatibility. Node.js key events are more commonly network events, including:

1. Response from web server
2. Read data from file
3. Return data from the database
To use the Events module we first need to create a new EventEmitter instance:

Copy code The code is as follows:

var EventEmitter= require('events').EventEmitter;
var test = new EventEmitter();

Once you add the above content to the code, you can add events and listeners. We can send events as follows, such as:

Copy code The code is as follows:

test.emit('msg','the message send by node');

The first parameter is a string describing the event so that it can be used for listener matching

In order to receive messages, you must add a listener, which handles the event when it is triggered, for example:

Copy code The code is as follows:

test.on('message',function(data){
console.log(data);
});

The Events module implements basic event listening mode methods such as addListener/on, once, removeListener, removeAllListeners, and emit. It is not the same as the events on the front-end DOM tree, because it does not have event behaviors belonging to the DOM such as bubbling and layer-by-layer capture, and there are no methods to handle event delivery such as preventDefault(), stopPropagation(), stopImmediatePropagation(), etc.

1. Class: events.EventEmitter: Obtain the EventEmitter class through require('events').EventEmitter.
2.emitter.on(event, listener): Add a listener to the end of the listener array for a specific event. Return emitter to facilitate chain calls, the same below.

3.emitter.removeListener(event, listener) removes a listener from the listener array of an event

4.emitter.listeners(event) returns the listener array of the specified event
For more details, see: Node.js API documentation

The following code shows a confidential message that can self-destruct in 5 seconds:

Copy code The code is as follows:

var EventEmitter = require('events').EventEmitter;
var secretMessage = new EventEmitter();

secretMessage.on('message', function (data) {
console.log(data);
});

secretMessage.on('self destruct', function () {
console.log('the msg is destroyed!');
});

secretMessage.emit('message','this is a secret message.It will self destruct in 5s');

setTimeout(function () {
secretMessage.emit('self destruct');
},5000);

In this script, two events are sent and there are two listeners. When the script is run, message events occur and are handled by the "message" handler

EventEmitter is used everywhere in Node.js, so it is important to master it. Node.js obtains data through I/O operations and extensively uses the Events module to support asynchronous programming

FAQ:

Q: Is there a limit to the maximum number of listeners for an event?
Answer: By default, if an event has 10 listeners operating on it, it will issue a warning. However, this number can be changed using emitter.setMaxListener(n)

Q: Is it possible to listen to all sent events?
Answer: No. We need to create listeners for each event we want to respond to

Statement
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Vercel是什么?怎么部署Node服务?Vercel是什么?怎么部署Node服务?May 07, 2022 pm 09:34 PM

Vercel是什么?本篇文章带大家了解一下Vercel,并介绍一下在Vercel中部署 Node 服务的方法,希望对大家有所帮助!

node.js gm是什么node.js gm是什么Jul 12, 2022 pm 06:28 PM

gm是基于node.js的图片处理插件,它封装了图片处理工具GraphicsMagick(GM)和ImageMagick(IM),可使用spawn的方式调用。gm插件不是node默认安装的,需执行“npm install gm -S”进行安装才可使用。

怎么使用pkg将Node.js项目打包为可执行文件?怎么使用pkg将Node.js项目打包为可执行文件?Jul 26, 2022 pm 07:33 PM

如何用pkg打包nodejs可执行文件?下面本篇文章给大家介绍一下使用pkg将Node.js项目打包为可执行文件的方法,希望对大家有所帮助!

一文解析package.json和package-lock.json一文解析package.json和package-lock.jsonSep 01, 2022 pm 08:02 PM

本篇文章带大家详解package.json和package-lock.json文件,希望对大家有所帮助!

分享一个Nodejs web框架:Fastify分享一个Nodejs web框架:FastifyAug 04, 2022 pm 09:23 PM

本篇文章给大家分享一个Nodejs web框架:Fastify,简单介绍一下Fastify支持的特性、Fastify支持的插件以及Fastify的使用方法,希望对大家有所帮助!

node爬取数据实例:聊聊怎么抓取小说章节node爬取数据实例:聊聊怎么抓取小说章节May 02, 2022 am 10:00 AM

node怎么爬取数据?下面本篇文章给大家分享一个node爬虫实例,聊聊利用node抓取小说章节的方法,希望对大家有所帮助!

手把手带你使用Node.js和adb开发一个手机备份小工具手把手带你使用Node.js和adb开发一个手机备份小工具Apr 14, 2022 pm 09:06 PM

本篇文章给大家分享一个Node实战,介绍一下使用Node.js和adb怎么开发一个手机备份小工具,希望对大家有所帮助!

图文详解node.js如何构建web服务器图文详解node.js如何构建web服务器Aug 08, 2022 am 10:27 AM

先介绍node.js的安装,再介绍使用node.js构建一个简单的web服务器,最后通过一个简单的示例,演示网页与服务器之间的数据交互的实现。

See all articles

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

AI Hentai Generator

AI Hentai Generator

Generate AI Hentai for free.

Hot Article

R.E.P.O. Energy Crystals Explained and What They Do (Yellow Crystal)
2 weeks agoBy尊渡假赌尊渡假赌尊渡假赌
Repo: How To Revive Teammates
1 months agoBy尊渡假赌尊渡假赌尊渡假赌
Hello Kitty Island Adventure: How To Get Giant Seeds
4 weeks agoBy尊渡假赌尊渡假赌尊渡假赌

Hot Tools

SAP NetWeaver Server Adapter for Eclipse

SAP NetWeaver Server Adapter for Eclipse

Integrate Eclipse with SAP NetWeaver application server.

MinGW - Minimalist GNU for Windows

MinGW - Minimalist GNU for Windows

This project is in the process of being migrated to osdn.net/projects/mingw, you can continue to follow us there. MinGW: A native Windows port of the GNU Compiler Collection (GCC), freely distributable import libraries and header files for building native Windows applications; includes extensions to the MSVC runtime to support C99 functionality. All MinGW software can run on 64-bit Windows platforms.

VSCode Windows 64-bit Download

VSCode Windows 64-bit Download

A free and powerful IDE editor launched by Microsoft

MantisBT

MantisBT

Mantis is an easy-to-deploy web-based defect tracking tool designed to aid in product defect tracking. It requires PHP, MySQL and a web server. Check out our demo and hosting services.

mPDF

mPDF

mPDF is a PHP library that can generate PDF files from UTF-8 encoded HTML. The original author, Ian Back, wrote mPDF to output PDF files "on the fly" from his website and handle different languages. It is slower than original scripts like HTML2FPDF and produces larger files when using Unicode fonts, but supports CSS styles etc. and has a lot of enhancements. Supports almost all languages, including RTL (Arabic and Hebrew) and CJK (Chinese, Japanese and Korean). Supports nested block-level elements (such as P, DIV),