Static resource management Services in Nodejs

Source: Internet
Author: User

Welcome everyone to guide and discuss:)

  First, what is static resources

  A static resource is a specific file that is placed on the server. More common are the. css,.png,. js files with these suffixes. This HTML page in the Logo.png to get to both the files in the server and the ASD.CSS. On the other, the server will return the corresponding MIME type and corresponding resources according to the request of these various resources.  Share a Query MimeType address http://www.freeformatter.com/mime-types-list.html#mime-types-list This article finally has the implementation code ~

Second, why the need for static resource management Services

So why do we need resource management services? For example, this HTML file, when we enter into the http://127.0.0.1/index.html (for example here), this file will not be the application of logo.png and ASD.CSS resources? Is there anything else we need to do? That's right. This file (HTML) does make a request for both resources. Such as. But please note that the pathname of the two request resources are not processed in the server, so the HTML file is not able to get nested inside the HTML of these files ~ For example, a mother for the first time with her two children to the library, mother of the library has a long pass ( In the server to the "mother" this request resource grant processing) ~ So, the administrator can let mom walk. But those two children, because there is no card (the server did not process the resource request), so that two children do not let go into the library. Therefore, we need to add an additional static resource management service to the server to handle these additional resource requests for corresponding processing (equivalent to building a card area in that library, librarian: "hey! You two! Go over there and get a card and you can go in! ").


Third , how to build static resource management Services

The solution is to return different mime-type based on the suffix of the resource being requested, and return the corresponding resource using a different resource's path. Simply put, according to the name of a classmate, go to the corresponding dorm, and then you can find him/her.

  Three. 1 mime-type

  Mime-type is a file with a different suffix, which has its corresponding MIME type (for example, Apple is a fruit, lettuce is a vegetable type). We return the resource together and return it with its corresponding MIME type so that the browser can correctly parse the resources we have returned based on this MIME resource. (Share: There is a need to FQ, but the more full MIME query site). Usually, we make a. json file of these suffix names and their corresponding MIME types so that the server can query.

  Three. 2 Building a static resource management service

  Let's start with a detailed procedure.

1. The server accepts the "/index" Request 2. The server returned a "index.html" Page 3. "Index.html" Issues resource request 4 for "logo.png" and "Asd.css". The server enters static resource Management Service Module 5. The management module gets the pathname and suffix names for both resource requests Extname 6. Define the specific path of the resource (__dirname + '/xxx ' + pathname or __dirname + pathname This will vary slightly from one architecture to another) 7. Gets the MIME type 8 for these two resources according to Mime_type.json. Depending on the path of the resource, the resource 9 is not present on the query server. Does not exist then returns 404 10. exists then reads the resource and returns it to the client (we have successfully built a managed service for static resources) 11. Cache Section please keep looking down O (∩_∩) o)

Iv. static resource caching in the browser

when We haven't set the resource cache yet (for example, just llogo.png and asd.css), even though the browser has downloaded the two resources through the server, but every time we refresh the browser, the browser will continue to pull the required resources from the server. and increased the pressure on the server. What we need to do is: when the browser refreshes again, let it get the corresponding resources from the local cache library (the first time the browser accesses the server and the resources downloaded from the server), instead of re-downloading it again from the server.

  Four. 1 attributes and if-modified-since of resources

  Every browser downloaded a good file, the browser will know the file (Resource) properties, including the file creation time, the file last modified time (if-modified-since) and so on some information. When a browser's local cache exists (such as a asd.css file), but it is not known that it is still in effect, the browser issues a conditional GET request, and If-modified-since is included in its request header. All we need to do is make a judgment: If the server file has changed after this time, the server sends the file to the client, if not changed, returns 304, does not send the file to the client, but instead lets the browser use the same name resource in the cache.

  Four. 2 expires and Cache-control

  The server takes the expires header when responding, and the browser determines the expires header until the specified date expires before a new request is initiated.

  Five , the whole code

/*Static_module.js*/varFS = require (' FS ');varSYS = require (' Util ');varHTTP = require (' http ');varurl = require (' URL '));varPath = require (' path ');varBase_dir =__dirname;varCONF = Base_dir + '/conf/';varSTATIC =Base_dir;varmimeconf =geturlconf ();varCache_time = 60*60*24*365; Exports.getstaticfile=function(Pathname, res, req) {varExtname =path.extname (pathname); Extname= Extname? Extname.slice (1): "; varRealpath = STATIC +pathname; varMimeType = Mimeconf[extname]? Mimeconf[extname]: ' Text/plain ';    Console.log (Extname); Fs.exists (Realpath,function(exists) {if(!exists) {Console.log (Realpath+ "is not found.") Res.writehead (404, {' Content-type ': ' Text/plain '}); Res.write (' Sorry, not Found this Source. ');        Res.end (); }Else{            varFileInfo =Fs.statsync (Realpath); varLastModified =fileInfo.mtime.toUTCString (); if(Mimeconf[extname]) {varDate =NewDate (); Date.settime (Date.gettime ()+ cache_time * 1000); Res.setheader ("Expires", date.toutcstring ()); Res.setheader ("Cache-control", "max-age=" +cache_time); Res.setheader ("Last-modified", lastmodified); }            if(req.headers[' if-modified-since ') && lastmodified = = req.headers[' if-modified-since ']) {Res.writehead (304, "Not Modified");            Res.end (); }Else{fs.readfile (Realpath,"Binary",function(err, file) {if(Err) {Res.writehead (, {' Content-type ': ' Text/plain '});                    Res.end (ERR); }Else{Res.writehead (The "Content-type": MimeType}); Res.write (file,"Binary");                    Res.end (); }                })            }        }    })}functiongeturlconf () {varRoutermsg = {}; Try{        varstr = fs.readfilesync (CONF + ' mime_type.json ', ' UTF8 '); Routermsg=json.parse (str); }Catch(e) {Sys.Debug ("JSON Parse Fails")    }    returnroutermsg;}

Resources

"Nodejs Development Actual combat detailed" P96

Static resource Management services in Nodejs

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.