Many Nodejs tutorials or books on the web teach you to call third-party modules to write NODEJS applications, although this is very handy, but the package is too thick for you to learn something basic. People's modules, people want to change the line, you can change the next version of the interface, your application is finished. For example, Google, he loves to do this kind of thing. So we have to honestly learn the underlying API.
This section first teaches you to run a page.
I wrote an article about a simple page output of node. js, so you can preview it first.
Generally speaking, everyone is getting started from such an example.
var http = require ("http"); Http.createserver (function (request, response) { Response.writehead (200, {") Content-type ":" Text/plain "}); Response.Write ("Hello node. js"); Response.End ();}). Listen (8888);
The above script is written on a app.js, then open the console, locate it in its directory, enter the node app, and then open a browser, input http://localhost:8888/to see the effect.
Analyze the above script:
- Introducing dependencies, which is a very magical thing before the front-end AMD spec is not popular. However, a project is so large, it must be divided into N directories n files, each responsible for a part, reduce the risk of merging conflicts
- Require ("http") spits out the HTTP object is a native object, similar to the front-end alert, setTimeout, is very common. This HTTP object is the backbone of the backend, and Web applications cannot do without it.
- The Http.createserver method is to receive a function, commonly called a callback. Later you will see more and more callbacks, theworld of Nodejs is the callback of the world, the history of Nodejs is a struggle with the callback history
- This callback is passed to you two important objects, the request object and the response object. Response to output something to the front, we need to set the response header (Response.writehead) and tell the browser what to do with our content. Because some things may be as script scripts, some as pictures, some as CSS files, and some to download as attachments ... response.write is used to output content. The output ends with a call to the End method, which is actually handy for response to perform an end callback.
- Http.createserver actually returns a server instance, which has a listen method, which is used to listen to a port at one end.
OK, that's it. Let's go into a little bit (it's harder here, you can skip it, just look at the next one ★).
Let's open this and look at the source code of the HTTP module, which probably calls the
_http_incoming_http_outgoing_http_server_http_client
These four important internal modules are not accessible to us in the NODEJS environment. HTTP also references other internal modules, but you can ignore them now. _http_incoming,_http_outgoing is to provide two input and output stream objects, stream is something we will focus on later. In this module, we remove the deprecated methods, mainly these three methods: Get, request, Createserver
I cut out the HTTP source code, and we'll understand what's going on:
------------------server------------------var server = require (' _http_server '); exports. Serverresponse = Server. Serverresponse;var Server = exports. Server = Server. Server;exports.createserver = function (requestlistener) { return new Server (Requestlistener);};/ /------------------Client------------------var client = require (' _http_client '); var clientrequest = exports. Clientrequest = client. Clientrequest;exports.request = function (options, CB) { return new Clientrequest (options, CB);}; Exports.get = function (options, CB) {//get is the package var req = exports.request (options, CB) of the request method; Req.end (); return req;};
So how did the Requestlistener go in? We went to the _http_server internal module and found that Serverresponse was just a subclass of Outgoingmessage, and the server instance was binding our Createserver callbacks through the request event. At the same time it also binds a Connectionlistener method through the connection event, connectionlistener the huge length, inside will emit request event.
if (!util.isundefined (req.headers.expect) && (req.httpversionmajor = = 1 && req.httpversionminor = = 1) && continueexpression.test (req.headers[' expect ')) { res._expect_continue = true; if (Eventemitter.listenercount (self, ' checkcontinue ') > 0) { self.emit (' checkcontinue ', req, res); } else { C7/>res.writecontinue (); Self.emit (' request ', req, res); } } else { self.emit (' request ', req, res); }
Res is an example of Serverresponse var res = new Serverresponse (req), req is a parseronincoming method, and Parseronincoming is A method of parser.onincoming. Trace to the _http_common internal module and find the following sentences:
Parser.onincoming (parser.incoming, info.shouldkeepalive)//There is no doubt that parser.incoming is our req object parser.incoming = New Incomingmessage (Parser.socket);
All right, all the truth, req is an example of incomingmessage , and Res is an example of serverresponse and outgoingmessage . Here has to spit groove, Nodejs source is too chaotic!
¡ï ★ We switch to Simple mode again. Knowing the above, we know why we need to focus on learning "class:http." Serverresponse "and" http. Incomingmessage ", if you have read the source of Express, you will find its request module and Response module on this extension.
Https://github.com/strongloop/express/blob/master/lib/request.jsvar req = Exports = Module.exports = { __proto_ _: http. Incomingmessage.prototype};//https://github.com/strongloop/express/blob/master/lib/response.jsvar res = Module.exports = { __proto__: http. Serverresponse.prototype};
A long time ago, we were using the Fs.readfile of the FS module to read a file on the server back to the front end:
var http = require ("http"), var fs = require (' FS '), Exports.start = function () { http.createserver (function (Request, Response) { fs.readfile ('./index.html ', ' utf-8 ', function (err, data) {//Read content if (err) throw err; Response.writehead ($, {"Content-type": "Text/html"});//note here Response.Write (data); Response.End (); }) . Listen (8888); Console.log ("Server start ...");
As already said, now is the time of the stream, response is a writable stream (corresponding to a readable stream), we create a readable stream on the line.
var http = require ("http"); var fs = require ("FS") Http.createserver (function (request, response) { var readable = fs.cr Eatereadstream ("./index.html") Response.writehead ($, {"Content-type": "Text/html"}); Readable.pipe (response);}). Listen (8888);
If an error occurs, you want to jump to page 404
var http = require ("http"); var fs = require ("FS") Http.createserver (function (request, response) { var readable = fs.cr Eatereadstream ("./index.html") Response.writehead ($, {"Content-type": "Text/html"}); Readable.pipe (response); Readable.on ("Error", function () { var readable = Fs.createreadstream ("./404.html") readable.pipe (response); }). Listen (8888);
Native Nodejs Learning Note 1