This article mainly introduces relevant information about the Community version of Node. js static file server. If you need it, please refer to it. First of all, thank github for providing the source code on github. Compared with last night's static file server, it is a little more complex and can learn a lot of new things.
The Code contains a fs. stat function and the pipe function of the ReadStream object. The stat function is used to obtain file information. The first parameter is the input file path, and the second parameter is the callback function. The second parameter stats of the callback function is the basic information of the file. The pipe function is used to connect the readable stream with the destination target writable stream. Data imported into this stream will be written into the destination stream. The source stream and Target stream can be synchronized by pausing and resuming the stream when necessary.
The improvement of the static file server lies in the use of the Last-Modified and If-Modified-Since packet headers. It is unnecessary to return existing files to the browser. By the way, gzip or deflate compression can be returned to resources based on the compression method requested by the browser.
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 (404, "Not Found", {'content-type': 'text/plain '}); response. write ("stats = "+ Stats); response. write ("This request URL" + pathname + "was 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 the file modification time var lastModified = stats. mtime. toUTCString (); var ifModifiedSince = "If-Modified-Since ". toLowerCase (); // set Last-Modified // The Last modification time Last-Modified response of the file returned by the server to the browser. 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 );} // The server receives the If-Modified-Since message header sent by the browser. // If the message header is the same as the date, the system returns the 304 message If the resource does not change. // The server notifies the browser that the resource already exists, if (request. headers [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 (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 ("Server runing at port:" + PORT + ". ");
The Expires field declares that a webpage or URL address is no longer cached by the browser. Once this time Expires, the browser should contact the original server. The expiration time is set to one year.
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"};
Lists the types of various resources. You can set the 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"};