A simple HTTP static file server written using Nodejs and Python

Source: Internet
Author: User
During the daily development process, we often need to modify some static files on the CDN (such as JavaScript, CSS, HTML files, etc.), in this process, we want to have a way to map the directory of the online CDN to a directory on the local hard disk, so that When we modify a file locally, we do not need to publish it, we can see the effect immediately after the refresh.

For example, our CDN domain name is: http://a.mycdn.com, local directory is: D:\workassets, we want all access to http://a.mycdn.com/* is mapped to the local d:\workassets\*. When you access http://a.mycdn.com/s/atp.js, you are actually reading the local D:\workassetss\atp.js, and you do not need to download the online files from the web.

Implementing this function is simple and the key points are as follows:

1, open an HTTP service locally, listen to 80 ports;
2, modify the system Hosts file, add "127.0.0.1 a.mycdn.com", the CDN domain name is bound to the local server address;
3, configure the local HTTP service, after receiving a GET request, first check the local hard disk for the existence of the corresponding file, if present, then return the contents of the file, if not present, return the corresponding content on the line.

As you can see, the key part is the need to build a local HTTP service. There are many tutorials in this area, such as installing Apache or Ngnix Server software locally, and then configuring the appropriate forwarding rules. But personally think this kind of method is still a bit complex, this article is to introduce, is another do not need to install the Server software method.

Because we are developing debugging locally, the requirements for performance and concurrency are not high, so we don't really need a professional HTTP software like Apache/ngnix, we just need a script that can provide HTTP services. such as using Nodejs to achieve.

Copy the Code code as follows:


/**
* AUTHOR:OLDJ
*
**/

var http = require ("http"),
url = require ("url"),
Path = require ("path"),
FS = require ("FS"),
Local_folders,
Base_url;

Local_folders = [//local path, Agent will look for files in this list directory, if not found then go to online address
"D:/work/assets"
];
Base_url = "http://10.232.133.214"; Line path, if the file is not found, then turn to this address


function LoadFile (pathname, response) {
var i, L = local_folders.length,
fn

Console.log ("Try to load" + pathname);

for (i = 0; i < L; i++) {

fn = local_folders[i] + pathname;
if (Path.existssync (FN) && Fs.statsync (FN). Isfile ()) {
Fs.readfile (FN, function (err, data) {
Response.writehead (200);
Response.Write (data);
Response.End ();
});

Return
}

}

Response.writehead (302, {
"Location": Base_url + pathname
});
Response.End ();
}

Http.createserver (
function (Request, response) {

var req_url = Request.url,
Pathname

Handling requests similar to HTTP://WWW.PHP.CN/,TBSP/TBSP.CSS?T=20110920172000.CSS
pathname = Req_url.indexof ("??") = =-1? Url.parse (Request.url). Pathname:req_url;
Console.log ("Request for" + pathname + "' received.");
LoadFile (pathname, response);

}). Listen (80);


Note change the values of the above local_folders and base_url two variables to the values you need. Save the file, such as Save as Local-cdn-proxy.js, then execute "node Local-cdn-proxy.js" on the command line, the local server is running, of course, do not forget to bind the hosts.

When a path is accessed through HTTP, the above script will be located in the local directory, and find the contents of the corresponding file, then the direct 302 jumps to the corresponding address on the line. In the case of missing, there is another way to do this is to download the corresponding content from the local server and return it, but for this requirement, the 302 jump is enough.

In addition to the Nodejs version, I have also written a Python version:


Copy the Code code as follows:


#-*-Coding:utf-8-*-
#
# AUTHOR:OLDJ
#

Import OS
Import Basehttpserver

Local_folders = [
"D:/work/assets"
]
Base_url = "http://10.232.133.214"

Class Webrequesthandler (Basehttpserver.basehttprequesthandler):

def do_get (self):
Print "Request for '%s ' received."% Self.path
For folder in Local_folders:
fn = os.path.join (folder, Self.path.replace ("/", OS.SEP) [1:])
If Os.path.isfile (FN):
Self.send_response (200)
Self.wfile.write (FN, "RB"). Read ())
Break

Else
Self.send_response (302)
Self.send_header ("Location", "%s%s"% (Base_url, Self.path))

Server = Basehttpserver.httpserver (("0.0.0.0", Webrequesthandler)
Server.serve_forever ()


As you can see, the Python version of the code is much leaner than the Nodejs version.

The above two-segment code is relatively simple, such as the Mime-type, content-length and other headers that do not have output content, and do not have special handling for possible blocking operations such as read file timeouts. For the local development environment, they are already working versions, and you can continue to expand both scripts to meet more requirements.

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.