search
HomeWeb Front-endJS TutorialA simple HTTP static file server written using nodejs and Python_node.js

In the daily development process, we often need to modify some static files (such as JavaScript, CSS, HTML files, etc.) placed on the CDN. In this process, we hope to have a way to map the online CDN directory to local A directory on the hard disk, so that when we modify a file locally, there is no need to publish it, and the effect can be seen immediately after refreshing.

For example, our CDN domain name is: http://a.mycdn.com, and the corresponding local directory is: D:workassets. We hope that all access to http://a.mycdn.com/* will be mapped Go to the local D:workassets*. For example, when you visit http://a.mycdn.com/s/atp.js, you are actually reading the local D:workassetssatp.js without downloading online files from the Internet.

It is very simple to implement this function, the key points are as follows:

1. Open an HTTP service locally and listen to port 80;
2. Modify the system hosts file, add "127.0.0.1 a.mycdn.com", and bind the CDN domain name to the local server address;
3. Configure the local HTTP service. After receiving a GET request, first check whether the corresponding file exists on the local hard disk. If it exists, the content of the file will be returned. If it does not exist, the corresponding content online will be returned.

As you can see, the key part is to build a local HTTP service. There are many tutorials in this area, such as installing server software such as Apache or Ngnix locally, and then configuring corresponding forwarding rules. However, I personally feel that this method is still a bit complicated. What this article will introduce is another method that does not require the installation of server software.

Because we are developing and debugging locally, the requirements for performance and concurrency are not high, so we actually do not need a professional HTTP software like Apache/Ngnix, we only need a script that can provide HTTP services That’s it. For example, use nodejs to implement it.

Copy code The code is 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, the agent will look for files in the directories in this list, and if not found, go to the online address
"D:/work/assets"
];
base_url = "http://10.232.133.214"; // Online path, if the file cannot be found, redirect to this address


function loadFile(pathname, response) {
var i, l = local_folders.length,
fn;

console.log("try to load " pathname);

for (i = 0; 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;

// Process requests similar to http://a.tbcdn.cn/??p/global/1.0/global-min.css,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);


Pay attention to modify the values ​​of the local_folders and base_url variables above to the values ​​you need. Save this file, for example, as local-cdn-proxy.js, and then execute "node local-cdn-proxy.js" on the command line. The local server will be running. Of course, don't forget to bind hosts.

When accessing a path through http, the above script will first search in the corresponding local directory. If found, it will return the content of the corresponding file. If it is not found, it will directly 302 jump to the corresponding online address. For situations where it cannot be found, another solution is to have the local server download the corresponding content from online and return it, but for this requirement, a 302 jump is enough.

In addition to the nodejs version, I also wrote a Python version:

Copy code The code is 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(open(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", 80), WebRequestHandler)
server.serve_forever()


可以看到,Python 版本的代码比 nodejs 版本的精简了很多。

上面的两段代码的功能还相对比较简单,比如没有输出内容的 MIME-Type、Content-Length 等头信息,对可能的阻塞操作(如读取文件超时等)也没有做特别的处理。对于本地开发环境来说,它们已经是可以工作的版本了,你也可以继续扩展这两个脚本,以便满足更多的需求。

Statement
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
JavaScript in Action: Real-World Examples and ProjectsJavaScript in Action: Real-World Examples and ProjectsApr 19, 2025 am 12:13 AM

JavaScript's application in the real world includes front-end and back-end development. 1) Display front-end applications by building a TODO list application, involving DOM operations and event processing. 2) Build RESTfulAPI through Node.js and Express to demonstrate back-end applications.

JavaScript and the Web: Core Functionality and Use CasesJavaScript and the Web: Core Functionality and Use CasesApr 18, 2025 am 12:19 AM

The main uses of JavaScript in web development include client interaction, form verification and asynchronous communication. 1) Dynamic content update and user interaction through DOM operations; 2) Client verification is carried out before the user submits data to improve the user experience; 3) Refreshless communication with the server is achieved through AJAX technology.

Understanding the JavaScript Engine: Implementation DetailsUnderstanding the JavaScript Engine: Implementation DetailsApr 17, 2025 am 12:05 AM

Understanding how JavaScript engine works internally is important to developers because it helps write more efficient code and understand performance bottlenecks and optimization strategies. 1) The engine's workflow includes three stages: parsing, compiling and execution; 2) During the execution process, the engine will perform dynamic optimization, such as inline cache and hidden classes; 3) Best practices include avoiding global variables, optimizing loops, using const and lets, and avoiding excessive use of closures.

Python vs. JavaScript: The Learning Curve and Ease of UsePython vs. JavaScript: The Learning Curve and Ease of UseApr 16, 2025 am 12:12 AM

Python is more suitable for beginners, with a smooth learning curve and concise syntax; JavaScript is suitable for front-end development, with a steep learning curve and flexible syntax. 1. Python syntax is intuitive and suitable for data science and back-end development. 2. JavaScript is flexible and widely used in front-end and server-side programming.

Python vs. JavaScript: Community, Libraries, and ResourcesPython vs. JavaScript: Community, Libraries, and ResourcesApr 15, 2025 am 12:16 AM

Python and JavaScript have their own advantages and disadvantages in terms of community, libraries and resources. 1) The Python community is friendly and suitable for beginners, but the front-end development resources are not as rich as JavaScript. 2) Python is powerful in data science and machine learning libraries, while JavaScript is better in front-end development libraries and frameworks. 3) Both have rich learning resources, but Python is suitable for starting with official documents, while JavaScript is better with MDNWebDocs. The choice should be based on project needs and personal interests.

From C/C   to JavaScript: How It All WorksFrom C/C to JavaScript: How It All WorksApr 14, 2025 am 12:05 AM

The shift from C/C to JavaScript requires adapting to dynamic typing, garbage collection and asynchronous programming. 1) C/C is a statically typed language that requires manual memory management, while JavaScript is dynamically typed and garbage collection is automatically processed. 2) C/C needs to be compiled into machine code, while JavaScript is an interpreted language. 3) JavaScript introduces concepts such as closures, prototype chains and Promise, which enhances flexibility and asynchronous programming capabilities.

JavaScript Engines: Comparing ImplementationsJavaScript Engines: Comparing ImplementationsApr 13, 2025 am 12:05 AM

Different JavaScript engines have different effects when parsing and executing JavaScript code, because the implementation principles and optimization strategies of each engine differ. 1. Lexical analysis: convert source code into lexical unit. 2. Grammar analysis: Generate an abstract syntax tree. 3. Optimization and compilation: Generate machine code through the JIT compiler. 4. Execute: Run the machine code. V8 engine optimizes through instant compilation and hidden class, SpiderMonkey uses a type inference system, resulting in different performance performance on the same code.

Beyond the Browser: JavaScript in the Real WorldBeyond the Browser: JavaScript in the Real WorldApr 12, 2025 am 12:06 AM

JavaScript's applications in the real world include server-side programming, mobile application development and Internet of Things control: 1. Server-side programming is realized through Node.js, suitable for high concurrent request processing. 2. Mobile application development is carried out through ReactNative and supports cross-platform deployment. 3. Used for IoT device control through Johnny-Five library, suitable for hardware interaction.

See all articles

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

Video Face Swap

Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Tools

MantisBT

MantisBT

Mantis is an easy-to-deploy web-based defect tracking tool designed to aid in product defect tracking. It requires PHP, MySQL and a web server. Check out our demo and hosting services.

SAP NetWeaver Server Adapter for Eclipse

SAP NetWeaver Server Adapter for Eclipse

Integrate Eclipse with SAP NetWeaver application server.

MinGW - Minimalist GNU for Windows

MinGW - Minimalist GNU for Windows

This project is in the process of being migrated to osdn.net/projects/mingw, you can continue to follow us there. MinGW: A native Windows port of the GNU Compiler Collection (GCC), freely distributable import libraries and header files for building native Windows applications; includes extensions to the MSVC runtime to support C99 functionality. All MinGW software can run on 64-bit Windows platforms.

PhpStorm Mac version

PhpStorm Mac version

The latest (2018.2.1) professional PHP integrated development tool

Atom editor mac version download

Atom editor mac version download

The most popular open source editor