Node. js: A simple page output implementation code _ javascript skills

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 you the trouble to forget the installation process. 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.

The Code is as follows:


Console. log ("hello node. js? 6.1.3 ")
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:

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

The Code is as follows:


For (var I in global ){
Console. log ("var" + I + "=" + global [I])
}


The result is as follows:

The Code 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 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:

The Code is as follows:


For (var I in module ){
Console. log ("var" + I + "=" + module [I])
}


The result is as follows:

The 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:

The 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 using anything starting with "get", which is supported by the latest browsers such as "set" and "get", for example, IE9. You can try the following script with the developer tool:

The Code is as follows:


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!

The 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? 6.1.3 ");
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.

The 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? 6.1.3 ");
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 ).

The Code is as follows:


Var server = require ("./server ");
Server. start ();


Then create an index.html page.

The Code is as follows:





Index





This is the homepage



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.

The 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:

The 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:

The Code is as follows:


Html, body {
Background: #3671A5;
Height: 100%
}


Then introduce the two files in index.html:

The Code is as follows:





Index



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.