SoFunction
Updated on 2025-03-09

Static file server improvement version

First of all, I would like to thank github for the author who provided this source code on github. It's a bit more complicated than what I came last night than today's static file server, and you can learn a lot of new things.

If you carefully find that this code has an additional function and a pipe function of the ReadStream object. The stat function is used to obtain file information. The first parameter is the file path, and the second is the callback function. The attribute of the second parameter of the callback function is the basic information of the file. The pipe function is used to connect this readable stream with the destination writable stream, and the data passed into this stream will be written to the destination stream. By pausing and restoring the flow when necessary, the source and destination flows are kept in sync.

The improvement of this static file server is that it uses Last-Modified and If-Modified-Since message headers, so that it is unnecessary to return files it already exists to the browser. By the way, you can return it to the resource according to the compression method of the browser requesting resources for gzip or deflate compression.

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 = (function(request, response) {
 ("Server", "Node/V5");
 var pathname = ().pathname;
 ("url = " + pathname);
 if ((-1) === "/") {
  pathname = pathname + ;
 }
 var realPath = __dirname + "/" + ("assets", ((/\.\./g, "")));
 ("realPath = " + realPath);
 var pathHandle = function (realPath) {
  (realPath, function (err, stats) {
   if (err) {
    (404, "Not Found", {'Content-Type': 'text/plain'});
    ("stats = " + stats);
    ("This request URL " + pathname + " was not found on this server.");
    ();
   } else {
    if (()) {
     realPath = (realPath, "/", );
     pathHandle(realPath);
    } else {
     var ext = (realPath);
     ext = ext ? (1) : 'unknown';
     var contentType = mime[ext] || "text/plain";
     ("Content-Type", contentType);
     //Get the file modification time     var lastModified = ();
     var ifModifiedSince = "If-Modified-Since".toLowerCase();
     //Set Last-Modified     //The server returns the last modification time of the file to the browser Last-Modified     ("Last-Modified", lastModified);

     if (()) {
      var expires = new Date();
      (() +  * 1000);
      ("Expires", ());
      ("Cache-Control", "max-age=" + );
     }
     //The server receives If-Modified-Since message header sent by the browser     //The same date means that the resource has not changed, and return 304     //Tell the browser that you already have the resource and no need to request it     if ([ifModifiedSince] && lastModified == [ifModifiedSince]) {
      (304, "Not Modified");
      ();
     } else {
      var raw = (realPath);
      var acceptEncoding = ['accept-encoding'] || "";
      var matched = (); 
      if (matched && (/\bgzip\b/)) {
       (200, "Ok", {'Content-Encoding': 'gzip'});
       (()).pipe(response);
      } else if (matched && (/\bdeflate\b/)) {
       (200, "Ok", {'Content-Encoding': 'deflate'});
       (()).pipe(response);
      } else {
       (200, "Ok");
       (response);
      }
     }
    }
   }
  });
 };

 pathHandle(realPath);
});
(PORT);
("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. Once this time is exceeded, the browser should contact the original server. The expiration time is set to 1 year.

 = {
 fileMatch: /^(gif|png|jpg|js|css)$/ig,
 maxAge: 60*60*24*365
};
 = {
 match: /css|js|html/ig
};
 = {
 file: ""
};

Enumerate the types of various resources, and you can set Content-Type according to the extension.

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