Node.js a simple page output to implement code _javascript skills

Source: Internet
Author: User
Tags assert documentation object object readfile setinterval
The installation process will not be said. If success is the command to use node. Node.js debugging is very convenient. Each of the background languages has a command to output pragmatics to that dark console. Node.js follows the FF set of things, that is, the console object and its methods. We first build a example.js file that reads as follows and then opens it on the console.
Copy Code code as follows:

Console.log ("Hello Node.js")
for (var i in console) {
Console.log (i+ "" +console[i])
}
Node Example.js.

You do not use alert in Node.js debugging, that is the browser with the global approach, do not blame the error.
The output results are as follows:
Copy Code code 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 (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:nanms ', label, duration);
}
var trace = function (label) {
TODO probably can to does this better with V8 ' s debug object once the IS
Exposed.
var err = new Error;
Err.name = ' Trace ';
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));
}
}

With these functions, we are probably aware of what Node.js has added to the global scope, such as require, process. But it cannot be arbitrarily said, because they may be private objects of a scope. However, understanding these global objects and starting from them to understand other objects is very helpful for us to understand the ecological structure of node.js. On the front end, whenever the browser is upgraded, I iterate over the window object and its element nodes to learn what methods and attributes it adds, and then look at the documentation. Those update logs are not going to tell you all the details and you have to walk through them yourself so you know more than anyone else. All right, let's go find Node.js's global object.
Node.js's documentation tells us that there are several global objects:
Global, process, require,__filename,__dirname, module
But why do we use Console.log directly? Experience tells us that console is definitely a member of a global object, as we can alert or window.alert. Well, let's take a walk through the name of global and get a very domineering object.
Copy Code code as follows:

for (var i in global) {
Console.log ("var" + i+ "=" +global[i])
}

The results are as follows:
Copy Code code 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 to omit
}
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]

Discover that global, like the browser window, has a member with the same name that points to itself. window = = Window.window, global = = Global.global. But Node.js was poorly designed in the early years, and a redundant global member was also engaged.
Console.log (Global = = Global.global)//true
Console.log (Global = = Global. GLOBAL)//true
We go through the module object again:
Copy Code code as follows:

for (var i in module) {
Console.log ("var" + i + "=" +module[i])
}

The results are as follows:
Copy Code code 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 to omit
}
var _compile = function (content, filename) {
Too long to omit
}

Originally the famous exports is provided here, __filename is probably also a reference to filename. Just walk through it and you'll find lots of interesting things. But do not think that the secret is exposed under your eyelids, there are many not traversal properties. For example, the above I traverse the global object, only Liao Liao can count several members, we can use ecma262v5 new method to investigate:
Console.log (Object.getownpropertynames (Global))
The results are as follows:
Copy Code code as follows:

[' Clearinterval ',
' TypeError ',
' decodeURI ',
' 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 ',
' decodeURIComponent ',
' Evalerror ',
' Cleartimeout ',
' GLOBAL ',
' SetInterval ',
' SyntaxError ',
' Object ',
' Eval ',
' Global ',
' Parseint ',
' JSON ',
' Isfinite ']

Many people learn node.js immediately look at their documents, but Node.js itself depends on the V8 engine has a lot to learn, which includes ecma262v5 new methods of new objects, as well as some of the syntax to emulate Firefox:
__definegetter__
__definesetter__
__lookupgetter__
__lookupsetter__
Set
Get
__proto__
But I don't recommend anything that starts with "__", like set and get, which is now supported by the latest browsers, such as IE9, to try the following script under its developer tools:
Copy Code code 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";
A.LOG[1] = "B";
Console.log (A.latest)

There is basically no compatibility problem with node.js (if you're not playing from the early Node.js), and the native object adds so much expansion, plus Node.js's own library, each module provides a variety of APIs, if not enough, GitHub there are thousands of plug-ins. This is tempting for jser who want to try back-end programming. It may be said that the backend does not involve database operations? This is nothing compared to the front-end DOM compatibility. What other folders and file operations you have as a special kind of array operation is. So you can be totally indignant!
All right, let's get some real stuff. Node.js is an HTTP server, it is to interact with the front-end, so there are no more than two objects: requests (request) and response (response). Request and response obviously an asynchronous thing, because we do not know when the front-end request to come, the response can not immediately to the front-end, but also to do log, read and write database operations. So for JavaScript, this is best achieved with a callback function. So who will accept this callback? A Server Object!
Copy Code code as follows:

var http = require ("http");
Http.createserver (function (request, response) {
Response.writehead ({"Content-type": "Text/plain"});
Response.Write ("Hello node.js");
Response.End ();
}). Listen (8888);

Node.js has a special require, which is used to synchronously load objects from other modules, similar to the require of other languages, import. It's good to sync, not a layer like the front end. Then use a function to instantiate a server object and then listen for Port 8888. This is the original Node.js official website example, everybody writes Rotten. But such a program in reality is useless, we enter the URL in the address bar, you should at least return to a complete page to me!
In this respect, we first need to be modular. Modularity is in the file as a unit, the example.js renamed to Server.js, and then the contents of the inside changed to a module. For a node.js file, the content inside it is actually executed in a closed environment. To be shared with other modules, you must bind to the exports object.
Copy Code code as follows:

var http = require ("http");
Exports.start = function () {
Http.createserver (function (request, response) {
Console.log ("Request received ...");
Response.writehead ({"Content-type": "Text/plain"});
Response.Write ("Hello node.js");
Response.End ();
}). Listen (8888);
Console.log ("Server start ...");
}

Then we build a index.js as a portal (Index.js and server.js in the same directory).
Copy Code code as follows:

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

Then build a index.html page.
Copy Code code as follows:

<!doctype html>
<title>index</title>
<meta content= "ie=8" http-equiv= "x-ua-compatible"/>
<meta http-equiv= "Content-type" content= "text/html; Charset=utf-8 ">

<body>
</body>

Now we are going to ask to come over, read the contents of this page and return it to the user. Then we need to use the FS module method.
Copy Code code 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 ({"Content-type": "Text/html"});/note here
Response.Write (data);
Response.End ();
});
}). Listen (8888);
Console.log ("Server start ...");
}

OK, then we restart the address again, we see a complete page.
But a page in addition to the HTML structure layer, there are JavaScript and CSS. So, we build a folder in the current directory javascripts, which is built in Index.js, the contents are as follows:
Copy Code code as follows:

Window.onload = function () {
var p = document.createelement ("P");
p.innerhtml = "This is dynamically added"
Document.body.appendChild (P);
}

To build a styles directory, which built INDEX.CSS, the following:
Copy Code code as follows:

html,body{
Background: #3671A5;
height:100%
}

The two files are then introduced in index.html:
Copy Code code as follows:

<!doctype html>
<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>
<body>
</body>

Re-open, found no change, Google, said to process JS and CSS file requests. There is no way to get the Request.url attribute, and then to determine the suffix name, for which the file read and set the header.
Copy Code code 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 suffix name
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, a plain JS file, a CSS file, an HTML file. The next goal is multiple pages, a Web site is composed of multiple purposes. It contains the following content, can handle AJAX requests, upload files, session and cookie support, log, MIME recognition, routing, caching system ... To do a lot of scary, so someone on the frame, and learning JS, even if the API has not been touched with jquery, then learn a hair! Looking back at the middle part of our server.js, we'll actually split the mime and the routing. But the most important thing is the same, how do you handle this infinite function nesting? I think this is not the same as my module loading system, the next time from here to do it.

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.