HTTP Server for Node.js
The low-level api,node.js using HTTP modules allow us to create servers and clients. When we first started learning node, we all encountered the following code:
Copy Code code as follows:
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 includes information about the HTTP module, which means:
1. Request HTTP modules from the core of ' node.js ' and assign a variable to be used in future scripts.
So the script can access some methods to use ' HTTP ' through ' node.js '.
2. Create a new Web server object using ' Createserver '
3. The script passes an anonymous function to the server telling the Web server object what happens whenever it receives a request
4. Script line 4th 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 headers
HTTP headers are sent for each HTTP request and response, and the HTTP hair sends the additional information, including the content type, the date the server sent the response, and the HTTP status code
HTTP header contains a lot of information, the following is my Baidu home page contains the HTTP header information:
Because of my Baidu home page to add more sites, so the data here and readers may not be the same. From which we can see that Baidu is a Web server is bws/1.1
Here is the HTTP header information for the code above:
Redirection in the Node.js
In node, we can easily create a simple server that redirects the visitor to another Web page with the following guidelines:
1. Send a 301 response code to the customer, telling the customer that the resource has been moved to another location;
2. Send a location header to tell the customer where to redirect to.
The relevant code is as follows:
Copy Code code 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");
Opening the browser to access the http://127.0.0.1:3000 page will be redirected.
Responding to different requests
Node.js not only can create a single response, but for multiple types of requests, we need to add some routing to the application. Node makes all this straightforward by using the URL module. The URL module allows us to read the URL, analyze it, and do something about the output.
Copy Code code as follows:
var url = require (' URL ');
var requesturl = "Http://example.com:1234/path?query=string"
Now we can parse the requested URL and intercept the content from it, for example, to get the host name, we can enter:
Copy Code code as follows:
Url.parse (requesturl). hostname
At this point, he will return to "example.com"
To obtain a port number, enter:
Copy Code code as follows:
Url.parse (requesturl). Port
He will return to "1234"
Event Module
Node.js is considered to be the best way to implement concurrency. The events (event) module is the core of node.js, and many other modules use it to surround the event architecture functionality. Because Node.js runs on a single thread, any synchronization code is blocked. So, when writing Node.js code, we need to consider some simple rules:
1. Don't block--' node.js ' is single-threaded, and if the code blocks, everything else stops.
2. Quick return-The operation should be returned quickly. If you cannot quickly return, you should migrate it to another process
The events module enables developers to set listeners and processors for the event. In client JS, we can set a listener for the click event and then do something when the event occurs:
Copy Code code 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 of not considering IE compatibility, node.js focus events are more common in network events, including:
1. Responses from the Web server
2. Reading data from a file
3. Returning data from a database
Using the Events module we first want to create a new Eventemitter instance:
Copy Code code as follows:
var eventemitter= require (' events '). Eventemitter;
var test = new Eventemitter ();
Once you have added the above to your code, you can add events and listeners, and we can send events as follows:
Copy Code code as follows:
Test.emit (' msg ', ' The message Send by node ');
The first parameter is the string that describes the event, so that the match for the listener
In order to receive the message, you must add a listener that the listener handles when the event is triggered, for example:
Copy Code code as follows:
Test.on (' message ', function (data) {
Console.log (data);
});
Events Module Addlistener/on,once,removelistener,removealllisteners,emit and other basic event listening mode implementation. It is not the same as the event on the front Dom tree, because it does not have event behaviors that are bubble-level, layer-by-step, Dom, and no Preventdefault (), Stoppropagation (), Stopimmediatepropagation () The method of handling event passing.
1. Class: Events. Eventemitter: Through require (' events '). Eventemitter gets the Eventemitter class.
2.emitter.on (event, listener): Adds a listener to the tail of a listener array of specific events. Return to emitter, easy to chain call, below.
3.emitter.removelistener (event, listener) deletes a listener from an event's listener array
4.emitter.listeners (event) returns the listener array of the specified event
For more information see: node.js API Documentation
The following code shows a confidential message that can self-destruct in 5 seconds:
Copy Code code 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 ', ' It is a secret message. It would self deatruct in 5s ');
settimeout (function () {
Secretmessage.emit (' self destruct ');
},5000);
In this script, two events were sent, with two listeners. When the script is run, the message event occurs and is handled by the "messages" processor
Eventemitter is used everywhere in node.js, so it is very important to master it. Node.js data obtained through I/O operations and extensive use of the events module to support asynchronous programming
Frequently Asked Questions:
Q: Is there a limit to the maximum number of listeners for an event?
A: By default, if an event has an operation of 10 listeners, it warns. However, you can use Emitter.setmaxlistener (n) to change this number
Q: Can I listen for all the events that are sent?
Answer: No. We need to create listeners for every event that we want to respond to