Nodejs common case Application Notes

Source: Internet
Author: User
Tags dio require

Nodejs enables the Http service and runs hello word

It is very easy to start a service in nodejs. We only need to install nodejs, find a directory, create a js file, copy the following code, and run it, you can enable the simplest http service for hello word!

Const http = require ('http ')

Const hostname = '2017. 0.0.1'
Const port = 3000
Const server = http. createServer (req, res) => {
Res. statusCode = 200
Res. setHeader ('content-type', 'text/plain ')
Res. end ('Hello World \ n ')
})

Server. listen (port, hostname, () => {
Console. log ('server running at http: // $ {hostname }:: {port }/')
})
As you can see, the above code uses ES6, and nodejs already supports most of ES6!

Introduction and application of key node. Js modules

// Http protocol module
Const http = require ('http ');
// Url parsing module
Const url = require ('URL ');
// File system module
Const fs = require ("fs ");
// Path parsing module
Const path = require ("path ");
For the common Operation Commands of the above basic modules, you can view the API on the official Node. Js website. If you think the English is hard to understand, you can read the following articles:

Fs module of nodejs

Nodejs Path module

Node. js Url & QueryString module

Of course, I will not write anything else! We use the above modules to create a simple nodejs service.

Path module application and 301 redirection

// If there is no extension in the path
If (path. extname (pathName) = ''){
// If it does not end with a slash (/), add/and perform 301 redirection.
If (pathName. charAt (pathName. length-1 )! = "/"){
PathName + = "/";
Var redirect = "http: //" + request. headers. host + pathName;
Response. writeHead (301 ,{
Location: redirect
});
Response. end ();
    }
// Add the default access page, but this page does not necessarily exist and will be processed later
PathName + = "index.html ";
HasExt = false; // indicates that the default page is automatically added by the program.
}
Fs reads the file list and 404 page

Fs. exists (filePath, function (exists ){
If (exists ){
Response. writeHead (200, {"content-type": contentType });
Var stream = fs. createReadStream (filePath, {flags: "r", encoding: null });
Stream. on ("error", function (){
Response. writeHead (500, {"content-type": "text/html "});
Response. end ("});
// Return the file content
Stream. pipe (response );
} Else {// The file name does not exist
If (hasExt ){
// If the file is not automatically added by the program, the system returns 404.
Response. writeHead (404, {"content-type": "text/html "});
Response. end ("} Else {
// If the file is automatically added by the program and does not exist, it indicates that the user wants to access the file list in the directory.
Var html = "

Try {
// User Access Directory
Var filedir = filePath. substring (0, filePath. lastIndexOf ('\\'));
// Obtain the file list in the user access path
Var files = fs. readdirSync (filedir );
// List all objects in the access path and add hyperlinks for further access
For (var I in files ){
Var filename = files [I];
Html + = "<div> <a href = '" + filename + "'>" + filename + "</a> </div> ";
                }
} Catch (e ){
Html + = "            }
Response. writeHead (200, {"content-type": "text/html "});
Response. end (html );
        }
    }
});
Console. time and console. timeEnd

We can use the following to output the execution time!

Console. time ('time ');
Console. timeEnd ("time ");
The two are used together.

Differences between exports and module. exports in nodejs

Nodejs we often use exports to create modules. But what are the specific differences between exports. XXX and module. exports? How to apply it?

Let's take a look at the application of exports. XXX:

Exports. name = function (){
Console. log ('My name is Haorooms ');
};
In another file, you reference

Var rocker = require ('./rocker. Js ');
Rocker. name (); // "My name is Haorooms"
Let's take a look at the following cases:

Module. exports = 'rock IT! ';
Exports. name = function (){
Console. log ('My name is Haorooms ');
};
Reference and execute rocker. js again

Var rocker = require ('./rocker. Js ');
Rocker. name (); // TypeError: Object rock it! Has no method 'name'
Error reported: Object "rock it !" No name method

The rocker module ignores the name method collected by exports and returns a string "rock it !". We can see that your module does not have to return an "instantiated object ". Your module can be any legal javascript Object-boolean, number, date, JSON, string, function, array, and so on.

Your module can be anything you set for it. If you have not explicitly set any attributes and methods for Module. exports, your Module is the attribute set for Module. exports. That is to say, Module. exports is the real interface, and exports is only a helper tool. The Module. exports instead of exports is returned.

Assume that your module is a constructor, as follows:

Module. exports = function (name, age ){
This. name = name;
This. age = age;
This. about = function (){
Console. log (this. name + 'is + this. age + 'ears old ');
};
};
You can apply it as follows:

Var Rocker = require ('./rocker. Js ');
Var r = new Rocker ('Oss ', 62 );
R. about (); // oearis 62 years old
Assume that your module is an array:

Module. exports = ['lew.kilmister', 'Oss Osbourne', 'Ronnie James Dio ', 'Steven count', 'Mick jarger'];
You can apply it as follows:

Var rocker = require ('./rocker. Js ');
Console. log ('Rockin heaven: '+ rocker [2]); // Rockin heaven: Ronnie James Dio
Now you understand that if you want your Module to be of a specific type, use Module. exports. If the module you want is a typical "instantiated object", use exports.

Github source code case

I have put the above nodejs case for enabling Http service on github. You can check it out!

Http: // localhost: 3000 // the contents in index.html are read.

Http: // localhost: 3000/werwer // The Display directory does not exist.

Http: // localhost: 3000/images // display the file list

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.