Nodejs implementation of a static server instance

  • 2020-03-30 04:32:23
  • OfStack

Refer to the static server example above cnodejs.org, write the following nodejs static server example, which contains cache, compression, paste code as follows:


/**
 * Static file server test example
 * User: xuwm
 * Date: 13-5-17
 * Time: In the morning 8:38
 * 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 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;   //By default, take index.html
from the current default     }
    var realPath = path.join("assets", path.normalize(pathname.replace(/../g, "")));
    console.log(realPath) ;
    var pathHandle=function(realPath){
    //Get the file
using the fs.stat method         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(" From the browser cache To get ")
                        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(/bgzipb/)) {
                            response.writeHead(200, "Ok", {'Content-Encoding': 'gzip'});
                            raw.pipe(zlib.createGzip()).pipe(response);
                        } else if (matched && acceptEncoding.match(/bdeflateb/)) {
                            response.writeHead(200, "Ok", {'Content-Encoding': 'deflate'});
                            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 of all, you need to create an assets folder in the JS file, which contains the static files you want to browse, such as index.html,demo. JS, etc.

To run it, switch to the above JS file directory on the command line and enter the node JS file name

Type http://localhost:3333/ in your browser and you'll see it.

Fill in the two modules missing from the above code

Mime. Js


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"
};

The config. Js


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