Node.js static file server Improved version _node.js

Source: Internet
Author: User

First of all, thank the GitHub, thank GitHub on the source of the author of this section. It's a little bit more complicated than the static file server that came last night, and you can learn a lot of new things.

Careful to discover that this code has a Fs.stat function and a Readstream object's pipe function, stat This function is used to get file information. The first parameter is the incoming file path, the second is the callback function, and the second parameter of the callback function, stats, is the basic information for the file. The pipe function is used to connect this readable stream with the destination target writable stream, and the data passed into the stream will be written to the destination stream. The source and destination streams are synchronized by pausing and resuming the stream if necessary.

The improvement point of this static file server is that the last-modified and if-modified-since headers are used, and you do not have to return the files that it already exists to the browser. By the way, you can return to the resource for gzip or deflate compression based on the compression of the browser's request resource.

var PORT = 8000;
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");
 var server = Http.createserver (function (request, response) {Response.setheader ("server", "node/v5");
 var pathname = Url.parse (request.url). Pathname;
 Console.log ("url =" + pathname); if (Pathname.slice ( -1) = = = "/") {pathname = pathname + CONFIG.
 Welcome.file;
 var Realpath = __dirname + "/" + Path.join ("Assets", Path.normalize (Pathname.replace (/\.\./g, "")));
 Console.log ("Realpath =" + Realpath); var pathhandle = function (Realpath) {fs.stat (Realpath, function (err, stats) {if (err) {Response.writehead (40
    4, "not Found", {' Content-type ': ' Text/plain '});
    Response.Write ("stats =" + stats);
    Response.Write ("This request URL" + pathname + "is not found on this server.");
   Response.End ();
    } else {if (Stats.isdirectory ()) { Realpath = Path.join (Realpath, "/", CONFIG.
     Welcome.file);
    Pathhandle (Realpath);
     else {var ext = path.extname (Realpath); Ext = ext?
     Ext.slice (1): ' Unknown '; var contentType = Mime[ext] | |
     "Text/plain";
     Response.setheader ("Content-type", ContentType);
     Get file modification time var lastmodified = stats.mtime.toUTCString ();
     var ifmodifiedsince = "If-modified-since". toLowerCase ();

     Set the last-modified//server to return the file to the browser last modified time last-modified 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); }//server receive browser sent over the same if-modified-since header//date indicates that the resource has not changed then return 304//Tell the browser that the resource you already have, do not need to request the IF (Request.header S[ifmodifiedsince] && LastModified = = Request.headers[ifmodifiedsince]) {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 (ok), {' content-encoding ': ' gzip
       '});
      Raw.pipe (Zlib.creategzip ()). pipe (response); else if (matched && acceptencoding.match (/\bdeflate\b/)) {response.writehead, OK, {' Content-encodi
       Ng ': ' deflate '});
      Raw.pipe (Zlib.createdeflate ()). pipe (response);
       else {response.writehead ("OK");
      Raw.pipe (response);
 }
     }
    }
   }
  });

 };
Pathhandle (Realpath);
});
Server.listen (PORT); Console.log ("Server runing at Port:" + Port + ".");

The Expires field declares the time when a Web page or URL address is no longer cached by the browser, and once this time is exceeded, the browser should contact the original server. This sets the expiration time to 1 years.

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

Enumerates the types of resources that can be set content-type according to the extension.

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

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.