Node. js provides a simple page output

Source: Internet
Author: User

Recently, I decided to refresh node. js and use it to merge JS files. Because I forgot about it, let's see if I can output a page first. Below are some of my notes, saving your time and forgetting to take a look ......

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.

 
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:

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 ('util'); process. stdout. write (UT Il. 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 | ''; erro R. 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.

 
For (var I in global) {console. Log ("Var" + I + "=" + global [I])}

The result is as follows:

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]

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) // trueconsole. Log (Global === global. Global) // true

Then we traverse the module object:

 
For (var I in Module) {console. Log ("Var" + I + "=" + module [I])}

The result is as follows:

 
VaR id =. vaR exports = [object] var parent = nullvar filename =/home/cheng19840218/node/example. jsvar loaded = falsevar exited = falsevar children = var paths =/home/cheng19840218/node/node_modules,/home/cheng19840218/node_modules,/home/node_modules, /node_modulesvar 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:

 
['Clearinterval', 'typeerror', 'codecuri ', 'buffer', 'parsefloat', 'number', 'urierror', 'encodeuricomponent', 'rangeerror ', 'referenceerror', 'regexp', 'array', 'isnan ', 'settimeout', 'console', 'date', 'infinity', 'boolean', 'error ', 'root', 'nan ', 'string', 'function', 'Math', 'undefined', 'encodeuri', '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 _ setget _ 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:

 
VaR A = {Get latest () {If (this. log. length> 0) {return this. log [this. log. length-1] ;}else {return NULL ;}, log: []}. log [0] = "A";. log [1] = "B"; console. log (. 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!

VaR HTTP = require ("HTTP"); http. createserver (function (request, response) {response. writehead (200, {"Content-Type": "text/plain"}); response. write ("Hello node. JS "); response. end ();}). listen (0, 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. HoweverProgramIn reality, nothing works. We enter a URL in the address bar. At least you have to return a complete page to 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.

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 ).

 
VaR Server = require ("./Server"); server. Start ();

Then create an index.html page.

 
<! Doctype 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.

 
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 the content if (ERR) Throw err; response. writehead (200, {"Content-Type": "text/html"}); // pay attention to 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:

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:

 
HTML, body {Background: #3671a5; Height: 100%}

Then introduce the two files in index.html:

 
<! Doctype HTML>  

re-open the file and find that it has not 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.

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 extension name switch (EXT) {Case ". CSS ": Case ". JS ": FS. readfile (". "+ request. URL, 'utf-8', function (ERR, data) {// read the 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 the 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.