node.js--static file Request module

Source: Internet
Author: User

"Implementing a static Resource management module"

/** *static_module.js */var base_dir = __dirname,//absolute path CONF = Base_dir + '/conf/',//conf file path static = BAS  E_dir + '/static ',//static file path mmieconf;  Used to store the Mmie json//file and its associated mmie type stored in Mmie_type.json, read this jsonvar getmmieconf = function () {var conf = {};  try{var confstr = fs.readfilesync (CONF + ' mmie_type.json ', ' UTF8 ');//synchronous Read File CONF = Json.parse (CONFSTR);  }catch{util.debug (' JSON parse fails '); } return conf;}; var util = require (' util '), FS = require (' FS '), HTTP = require (' http '), url = require (' URL '), Path = require (' Path '); mmieconf = getmmieconf ();//Get Static file interface//pathname: Static file relative path Req:requset Object Res:response Object exports.getstaticfile =  function (pathname, req, res) {var extname = path.extname (pathname); The path module's Extname method can get the file suffix of the URL, such as '. html ' extname = extname? Extname.slice (1): ";  ' html ' var realpath = STATIC + pathname; var mmietype = Mmieconf[extname] | |    ' Text/plain '; Fs.exists (Realpath, function (exsit) {//Determine if the file exists if (!exsit {//If not present, return 404 Res.writehead (404, {' Content-type ': ' Text/plain '});      Res.write (' The file in ' + pathname + ' is not found ');    Res.end (); }else{//If the file exists, determine if the file conforms to the cache condition, return 304 if compliant, non-compliant read the static file return var FileInfo = Fs.statsync (Realpath);      Fs.statsync gets the file-related information, returns a JSON, where the Mtime property records the last modified time of the file var lastmodifiedtime = fileInfo.mtime.toUTCString ();        Sets the cache-related header if (Mmieconf[extname]) {var date = new Date ();      Res.setheader (' Expires ', date.toutcstring ());//Set Expiration Time Res.setheader (' Cache-control ', ' max-age= ' + 60*60*24*365); }//Decide whether to expire, if not expired on 304, has expired to read the file if (req.headers[' if-modified-since ') && lastmodifiedtime = req.header[' If-modified-since ']) {The header in the//req object has the last modified time of the record file, if and the last modified time of the service//device        To the documentation has not been changed, 304 is good res.writehead (304, ' not modified ');      Res.end (); }else{//read static file Fs.readfile (Realpath, ' binary ', function (err, file) {if (err) {//Read file error(Res.writehead, ' content-type:plain ');          Res.end (ERR);            }else{res.setheader (' last-modified ', lastmodifiedtime);            Res.writehead (' $ ', {' Content-type ': Mmietype});            Res.write (file, ' binary ');          Res.end (); }        })      }    }  });}

  

Use this module:

var staticmodule = require ('./static_module '); Http.createserver (function (res, req) {    var pathname = Url.parse ( Req.url). pathname;//Gets the relative path    if (pathname = = '/favicon.ico ') {        return;    } else if (pathname = = '/index ' | | pathname = = '/') {        gotoindex ();    } else{        staticmodule.getstaticfile (pathname, req, res);    });                

  

  

node.js--static file Request module

Related Article

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.