A static server instance implemented by Nodejs and a nodejs static instance

Source: Internet
Author: User

A static server instance implemented by Nodejs and a nodejs static instance

Refer to the static server example at cnodejs.org and write the following nodejs static server example, which contains cache, compression, and the following code:
Copy codeThe Code is as follows:
/**
* Static file server test example
* User: xuwm
* Date: 13-5-17
* Time: AM
* To change this template use File | Settings | File Templates.
*/
Var port = 3333;
Var http = require ("http ");
Var url = require ("url ");
Var fs = require ("fs ");
Var path = require ("path ");
Var mime = require ("./mime"). types;
Var config = require ("./config ");
Var zlib = require ("zlib ");
// Create an http server
Var server = http. createServer (function (request, response ){
Var obj = url. parse (request. url );
Response. setHeader ("Server", "Node/V8 ");
Console. log (obj );
Var pathname = obj. pathname;
If (pathname. slice (-1) = "/"){
Pathname = pathname + config. Welcome. file; // retrieve the index.html file from the current directory.
}
Var realPath = path. join ("assets", path. normalize (pathname. replace (/\. \./g ,"")));
Console. log (realPath );
Var pathHandle = function (realPath ){
// Use the fs. stat method to obtain the file
Fs. stat (realPath, function (err, stats ){
If (err ){
Response. writeHead (404, "not found", {'content-type': 'text/plain '});
Response. write ("the request" + realPath + "is not found ");
Response. end ();
} Else {
If (stats. isDirectory ()){
} Else {
Var ext = path. extname (realPath );
Ext = ext? Ext. slice (1): 'unknown ';
Var contentType = mime [ext] | "text/plain ";
Response. setHeader ("Content-Type", contentType );

Var lastModified = stats. mtime. toUTCString ();
Var ifModifiedSince = "If-Modified-Since". toLowerCase ();
Response. setHeader ("Last-Modified", lastModified );

If (ext. match (config. Expires. fileMatch )){
Var expires = new Date ();
Expires. setTime (expires. getTime () + config. Expires. maxAge * 1000 );
Response. setHeader ("Expires", expires. toUTCString ());
Response. setHeader ("Cache-Control", "max-age =" + config. Expires. maxAge );
}

If (request. headers [ifModifiedSince] & lastModified = request. headers [ifModifiedSince]) {
Console. log ("retrieve from browser cache ")
Response. writeHead (304, "Not Modified ");
Response. end ();
} Else {
Var raw = fs. createReadStream (realPath );
Var acceptEncoding = request. headers ['Accept-encoding '] | "";
Var matched = ext. match (config. Compress. match );

If (matched & acceptEncoding. match (/\ bgzip \ B /)){
Response. writeHead (200, "OK", {'content-encoding': 'gzip '});
Raw. pipe (zlib. createGzip (). pipe (response );
} Else if (matched & acceptEncoding. match (/\ bdeflate \ B /)){
Response. writeHead (200, "OK", {'content-encoding': 'release '});
Raw. pipe (zlib. createDeflate (). pipe (response );
} Else {
Response. writeHead (200, "OK ");
Raw. pipe (response );
}
}
}
}
});

}
PathHandle (realPath );
});
Server. listen (port );
Console. log ("http server run in port:" + port );

First, create an assets folder in the js file, and add the static files you want to view, such as index.html and demo. js.

Run the following command: switch to the JS file directory in the command line, and enter the node JS file name.

Enter http: // localhost: 3333/in the browser to see the effect.

-- Add the two modules missing in the above Code

Mime. js

Copy codeThe Code is as follows:
Exports. types = {

"Css": "text/css ",

"Gif": "image/gif ",

"Html": "text/html ",

"Ico": "image/x-icon ",

"Jpeg": "image/jpeg ",

"Jpg": "image/jpeg ",

"Js": "text/javascript ",

"Json": "application/json ",

"Pdf": "application/pdf ",

"Png": "image/png ",

"Svg": "image/svg + xml ",

"Swf": "application/x-shockwave-flash ",

"Tiff": "image/tiff ",

"Txt": "text/plain ",

"Wav": "audio/x-wav ",

"Wma": "audio/x-ms-wma ",

"Wmv": "video/x-ms-wmv ",

"Xml": "text/xml"
};

Config. js

Copy codeThe Code is as follows:
Exports. Expires = {
FileMatch:/^ (gif | png | jpg | js | css) $/ig,
MaxAge: 60*60*24*365
};

Exports. Compress = {
Match:/css | js | html/ig
};

Exports. Welcome = {
File: "index.html"
};

Related Article

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.