This article mainly introduces a static server instance implemented by Nodejs. The static server instance implemented in this article includes the cache and compression functions, for more information, see the static server example at cnodejs.org and write the following node. js static server example, which contains cache, compression, and the following code:
The 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
The 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
The 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"
};