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 all encountered the following code:
The code copy is 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, meaning:
1. Request the HTTP module from the core of `Node.js` and assign a variable to use in future scripts.
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. The script line 4 defines the port and host of the web server, which means that `http://127.0.0.1:3000` can be used
Visit the server
Http header
For each 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 information about the http header included in my Baidu homepage:
Since I have added more websites to my Baidu homepage, the data here may be different from those of readers. From this we can see that Baidu is a web server and BWS/1.1
Below is the http header information of the code above just now:
Redirection in Node.js
In node, we can easily create a simple server to redirect visitors 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.
The relevant codes are as follows:
The code copy 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 the http://127.0.0.1:3000 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 URL modules. The URL module allows us to read the URL, analyze it and then do something with the output.
The code copy 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 cut the content from it, for example, to get the host name, we can enter:
The code copy is as follows:
url.parse(requestURL).hostname
At this time, he will return to "example.com"
To obtain the port number, you can enter:
The code copy is as follows:
url.parse(requestURL).port
He will return to "1234"
Event module
Node.js is considered the best way to achieve concurrency. The Events module is the core of Node.js, and many other modules use it to surround event architecture functionality. Since Node.js runs in a single thread, any synchronous code is blocked. Therefore, 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 return quickly. If you cannot return quickly, you should migrate it to another process
The Events module allows developers to set up listeners and processors for events. In client js we can set a listener for the click event and then do something when the event occurs:
The code copy 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, and the Node.js focus events are more common to network events, including:
1. Response from the web server
2. Read data from the file
3. Return data from the database
Using the Events module, we first need to create a new EventEmitter instance:
The code copy is as follows:
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, such as:
The code copy is as follows:
test.emit('msg','the message send by node');
The first parameter is a string that describes the event so that it can be used for the listener's matching
In order to receive a message, a listener must be added, which handles it when the event is triggered, for example:
The code copy is as follows:
test.on('message',function(data){
console.log(data);
});
The basic event listening mode implementation of 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 event behaviors that belong to the DOM such as bubbles, layer by layer capture, and there is no way to handle event delivery such as preventDefault(), stopPropagation(), stopImmediatePropagation(), etc.
1.Class: events.EventEmitter: Get the EventEmitter class through require('events').EventEmitter.
2.emitter.on(event, listener): Add a listener to the tail of the listener array of a specific event. Return to emitter, facilitate chain call, the same below.
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
See the Node.js API documentation for more details
The following code shows a confidential message that can self-destruct within 5 seconds:
The code copy 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 death in 5s');
setTimeout(function () {
secretMessage.emit('self destruct');
},5000);
In this script, two events are sent, with two listeners. When the script is running, the message event occurs and is processed by the "message" processor
EventEmitter is used everywhere in Node.js, so it is important to master it. Node.js obtains data through I/O operations and widely uses the Events module to support asynchronous programming
FAQ:
Q: Is there a limit on the maximum number of listeners for an event?
A: By default, if the event has 10 listeners operating, it will issue a warning. However, you can use emitter.setMaxListener(n) to change this quantity
Q: Can I listen to all sent events?
Answer: No. We need to create a listener for each event we want to respond to