Node. js: A simple page output implementation code

Source: Internet
Author: User

The installation process will not be mentioned. If it succeeds, you can use the node command. Node. js debugging is very convenient. Each background language has a command to output a pragmatic command to the console Group of the Black hacker. Node. js follows the FF set, that is, the console object and its method. First, create an example. js file with the following content, and then open it on the console. Copy codeThe Code is as follows: console. log ("hello node. js ")
For (var I in console ){
Console. log (I + "" + console [I])
}
Node example. js.

You must never use alert for debugging in node. js. It is a global method in the browser. It is not surprising that no error is reported.
The output result is as follows:Copy codeThe Code is as follows: var log = function (){
Process. stdout. write (format. apply (this, arguments) + '\ n ');
}
Var info = function (){
Process. stdout. write (format. apply (this, arguments) + '\ n ');
}
Var warn = function (){
WriteError (format. apply (this, arguments) + '\ n ');
}
Var error = function (){
WriteError (format. apply (this, arguments) + '\ n ');
}
Var dir = function (object ){
Var util = require ('til ');
Process. stdout. write (util. inspect (object) + '\ n ');
}
Var time = function (label ){
Times [label] = Date. now ();
}
Var timeEnd = function (label ){
Var duration = Date. now ()-times [label];
Exports. log ('undefined: nanm', label, duration );
}
Var trace = function (label ){
// TODO probably can to do this better with V8's debug object once that is
// Exposed.
Var err = new Error;
Err. name = 'track ';
Err. message = label | '';
Error. captureStackTrace (err, arguments. callee );
Console. error (err. stack );
}
Var assert = function (expression ){
If (! Expression ){
Var arr = Array. prototype. slice. call (arguments, 1 );
Require ('assert '). OK (false, format. apply (this, arr ));
}
}

Through these functions, we probably know what node. js has added to the global scope, such as require and process. But it cannot be said arbitrarily because they may be private objects in a specific scope. However, understanding these global objects and understanding other objects from these objects can help us understand the node. js ecosystem structure. At the front end, whenever the browser is upgraded, I traverse the window object and its element nodes to find out what methods and attributes it has added, and then check the document. The updated logs cannot tell you all the details. You must traverse them by yourself so that you know more than others. Now, let's look for the Global Object of node. js.
The node. js document tells us that there are several global objects:
Global, process, require ,__ filename ,__ dirname, module
But why can we directly use console. log? Experience tells us that the console must be a member of a global object, just as we can use alert or window. alert. Okay, let's traverse the global name to get a very domineering object.Copy codeThe Code is as follows: for (var I in global ){
Console. log ("var" + I + "=" + global [I])
}

The result is as follows:Copy codeCode: var global = [object global]
Var process = [object EventEmitter]
Var GLOBAL = [object global]
Var root = [object global]
Var Buffer = function Buffer (subject, encoding, offset ){
// Too long, omitted
}
Var setTimeout = function (){
Var t = NativeModule. require ('timers ');
Return t. setTimeout. apply (this, arguments );
}
Var setInterval = function (){
Var t = NativeModule. require ('timers ');
Return t. setInterval. apply (this, arguments );
}
Var clearTimeout = function (){
Var t = NativeModule. require ('timers ');
Return t. clearTimeout. apply (this, arguments );
}
Var clearInterval = function (){
Var t = NativeModule. require ('timers ');
Return t. clearInterval. apply (this, arguments );
}
Var console = [object Object]

It is found that global, like the window in the browser, has a member with the Same Name Pointing to itself. Window === window. window, global === global. global. However, node. js was poorly designed in the early days and made a redundant GLOBAL member.
Console. log (global === global. global) // true
Console. log (global === global. GLOBAL) // true
Then we traverse the module object:Copy codeThe Code is as follows: for (var I in module ){
Console. log ("var" + I + "=" + module [I])
}

The result is as follows:Copy codeThe Code is as follows: var id =.
Var exports = [object Object]
Var parent = null
Var filename =/home/cheng19840218/node/example. js
Var loaded = false
Var exited = false
Var children =
Var paths =/home/cheng19840218/node/node_modules,/home/cheng19840218/node_modules,/home/node_modules,/node_modules
Var load = function (filename ){
// Too long, omitted
}
Var _ compile = function (content, filename ){
// Too long, omitted
}

The famous exports was originally provided here, where __filename is probably referenced by filename. As long as you traverse it, you will find many interesting things. But do not think that the secret is under your eyes, and there are many attributes that cannot be traversed. For example, if I traverse the global Object above and there are only a few Members in zookeeper, we can use the new method ecma262v5 to check it:
Console. log (Object. getOwnPropertyNames (global ))
The result is as follows:Copy codeThe Code is as follows: ['clearinterval ',
'Typeerror ',
'Decodeuri ',
'Buffer ',
'Parsefloat ',
'Number ',
'Urierror ',
'Enablecomponent ',
'Rangeerror ',
'Referenceerror ',
'Regexp ',
'Array ',
'Isnan ',
'Settimeout ',
'Console ',
'Date ',
'Infinity ',
'Boolean ',
'Error ',
'Root ',
'Nan ',
'String ',
'Function ',
'Math ',
'Undefined ',
'Enaburi ',
'Escape ',
'Unescape ',
'Process ',
'Desturicomponent ',
'Evalerror ',
'Cleartimeout ',
'Global ',
'Setinterval ',
'Syntaxerror ',
'Object ',
'Eval ',
'Global ',
'Parseint ',
'Json ',
'Isfinite ']

Many people learn node. js immediately reads its documentation, but does not know node. js itself relies on the V8 engine to have a lot of things to learn, including new methods and objects brought about by ecma262v5, and some syntax similar to firefox:
_ DefineGetter __
_ DefineSetter __
_ LookupGetter __
_ LookupSetter __
Set
Get
_ Proto __
However, I do not recommend that you use anything starting with "_", such as the latest browsers supported by set and get, such as IE9, you can try the following script with the developer tool:Copy codeCode: var a = {
Get latest (){
If (this. log. length> 0 ){
Return this. log [this. log. length-1];
}
Else {
Return null;
}
},
Log: []
}
A. log [0] = "";
A. log [1] = "B ";
Console. log (a. latest)

In node. javascript basically has no compatibility issues (if you are not from the early node. js), and the Native object has added so many extensions, plus node. each module provides a wide range of APIS for the library provided by js. If it is not enough, there are thousands of plug-ins on github. This is tempting for the JSer who wants to try back-end programming. Some people may say that the backend does not involve database operations? This is not worth mentioning in comparison with the frontend DOM compatibility. What other folder and file operations do you think of as a special array operation. So you can be angry!
Okay, let's get some substantive content. Node. js is originally an http server and needs to interact with the front-end. Therefore, there are two objects: request and response ). The request and response are obviously asynchronous, because we do not know when the front-end sends a request, and the response cannot be immediately sent to the front-end. We also need to perform operations such as logging and reading and writing the database. Therefore, for javascript, it is best to use the callback function. Who will accept this callback? A server object!Copy codeThe Code is as follows: 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 );

Node. js has a special require used to synchronously load objects of other modules, which is similar to require and import in other languages. Synchronization is good, not as well as a layer-by-layer front-end. Then, a function is used to instantiate a Server Object and listen to port 8888. This is the first example on the node. js official website. But such a program is useless in reality. We enter a URL in the address bar. At least you have to return a complete page for me!
In this regard, we must first modularize. Modularization is based on files. example. js is renamed as server. js, And the content in it is changed to a module. For a node. js file, the content in it is actually executed in a closed environment. To be shared with other modules, you must bind them to the exports object.Copy codeThe Code is as follows: var http = require ("http ");
Exports. start = function (){
Http. createServer (function (request, response ){
Console. log ("Request received ed ...");
Response. writeHead (200, {"Content-Type": "text/plain "});
Response. write ("Hello node. js ");
Response. end ();
}). Listen (8888 );
Console. log ("server start ...");
}

Then we create an index. js as the entry (index. js and server. js are placed in the same directory ).Copy codeThe Code is as follows: var server = require ("./server ");
Server. start ();

Then create an index.html page.Copy codeThe Code is as follows: <! Doctype html>
<Html>
<Head>
<Title> index </title>
<Meta content = "IE = 8" http-equiv = "X-UA-Compatible"/>
<Meta http-equiv = "Content-Type" content = "text/html; charset = UTF-8">

</Head>
<Body>
<H2> This is the home page </Body>
</Html>

Now, we will read the content of this page and return it to the user. In this case, we need to use the fs module method.Copy codeThe Code is as follows: 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 (200, {"Content-Type": "text/html"}); // pay attention to this
Response. write (data );
Response. end ();
});
}). Listen (8888 );
Console. log ("server start ...");
}

Now, restart and enter the address again to see a complete page.
However, in addition to the HTML structure layer, a page also contains javascript and css. Then, create a folder named javascripts in the current directory and create index. js. The content is as follows:Copy codeThe Code is as follows: window. onload = function (){
Var p = document. createElement ("p ");
P. innerHTML = "this is dynamically added"
Document. body. appendChild (p );
}

Create another style directory with index.css as follows:Copy codeThe Code is as follows: html, body {
Background: #3671A5;
Height: 100%
}

Then introduce the two files in index.html:Copy codeThe Code is as follows: <! Doctype html>
<Html>
<Head>
<Title> index </title>
<Meta content = "IE = 8" http-equiv = "X-UA-Compatible"/>
<Meta http-equiv = "Content-Type" content = "text/html; charset = UTF-8">
<Link type = "text/css" rel = "stylesheet" href = "styles/index.css"/>
<Script src = "/javascripts/index. js"> </script>
</Head>
<Body>
<H2> This is the home page </Body>
</Html>

Re-open the file and find it hasn't changed. google said it wants to process js and css file requests. There is no way to obtain the request. url attribute, and then determine the suffix to read the file and set the header for it.Copy codeThe Code is as follows: var http = require ("http ");
Var fs = require ('fs ');
Var url = require ('url ');
Exports. start = function (){
Http. createServer (function (request, response ){
Var pathname = url. parse (request. url). pathname;
Var ext = pathname. match (/(\. [^.] + |) $/) [0]; // get the suffix
Switch (ext ){
Case ". css ":
Case ". js ":
Fs. readFile ("." + request. url, 'utf-8', function (err, data) {// read content
If (err) throw err;
Response. writeHead (200 ,{
"Content-Type ":{
". Css": "text/css ",
". Js": "application/javascript ",
} [Ext]
});
Response. write (data );
Response. end ();
});
Break;
Default:
Fs. readFile ('./index.html', 'utf-8', function (err, data) {// read content
If (err) throw err;
Response. writeHead (200 ,{
"Content-Type": "text/html"
});
Response. write (data );
Response. end ();
});
}
}). Listen (8888 );
Console. log ("server start ...");
}


So far, the purpose of this article has been achieved. Three node. js files, one common js file, one css file, and one html file. The next goal is to create multiple pages. A website consists of multiple purposes. It contains the following content, which can process ajax requests, upload files, Session and Cookie support, logs, MIME identification, route distribution, cache system ...... there are so many scary things to do, so someone can use jQuery as soon as they are familiar with JavaScript! Let's look back at the middle part of server. js above. In fact, we need to split the MIME and route. But the most important thing is how to deal with the infinite function nesting? I think this is no different from my module loading system. Let's start from here next time.

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.