HTTP and event modules in Node. js

Source: Internet
Author: User
Tags emit
This article describes in detail the relevant information of the HTTP module and event module in Node. js. If you need more information, refer to the http server of Node. js.

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

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

This Code contains information about the http module, which means:

1. Request the HTTP module from the core of 'node. js' and assign a variable for use in future scripts.
Therefore, the script can access some methods to use '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 what happens to an object 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: 8080'
To access the server

Http Header

For each HTTP request and response, an HTTP header sends additional information, including the content type, the server's response date, And the HTTP status code.

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

The related 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");

Access the http: // 127.0.0.1: 3000 page in a browser will be redirected.

Respond to different requests

Node. js can not only create a single response, but also add routes to applications for various types of requests. Node makes all this straightforward by using the URL module. The URL module allows us to read the URL, analyze it, And then perform some operations on the output.

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

Now, we can analyze the request URL and extract content from it. For example, to obtain the host name, we can enter:

url.parse(requestURL).hostname

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

To obtain the port number, enter:

url.parse(requestURL).port

He will return "1234"


Event Module

Node. js is considered to be the best way to achieve concurrency. The Events module is the core of Node. js, and many other modules use it to focus on the event architecture functions. Because Node. js runs in a single thread, any synchronization code is blocked. Therefore, when writing Node. js code, we should consider some simple rules:

1. Don't block it -- 'node. js' is single-threaded. If the code is blocked, everything else stops.
2. Quick Return-the operation should return quickly. If it cannot be returned quickly, it should be migrated to another process.
The Events module allows developers to set listeners and processors for Events. In client js, we can set a listener for the Click Event and execute some tasks when the event occurs:

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. The most common Node. js events are network events, including:

1. response from web Server
2. read data from a file
3. return data from the database
To use the Events module, we must first create a new EventEmitter instance:

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

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

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

The first parameter is a string that describes the event for the listener to match.

To receive a message, you must add a listener that processes it when an event is triggered. For example:

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

The Events module addListener/on, once, removeListener, removeAllListeners, emit, and other basic event listening modes. It is not the same as the events on the front-end DOM tree, because it does not have bubbles, layer-by-layer capture and other DOM-related event behaviors, and does not have preventDefault (), stopPropagation (), stopImmediatePropagation () and other methods to handle event transfer.

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 of a specific event. Emitter is returned to facilitate chained calling.

3. emitter. removeListener (event, listener) deletes 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 be self-destroyed within five seconds:

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 deatruct in 5s');setTimeout(function () {   secretMessage.emit('self destruct');},5000);

In this script, two events are sent, with two listeners. When the script runs, a message event occurs and is processed by the "message" processor.

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

FAQs:

Q: Is there a limit on the maximum number of listeners for an event?
A: By default, if the event has 10 listeners, it will issue a warning. However, you can use emitter. setMaxListener (n) to change this quantity.

Q: Can I listen on all sent events?
A: No. We need to create a listener for each event to respond.

For more details about the HTTP and event modules in Node. js, please follow the PHP Chinese network!

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.