Sample code for actual node static file server
This article mainly introduces examples of actual node static file servers. Now I share them with you and give them a reference.
This article mainly introduces examples of actual node static file servers and shares them with everyone. The details are as follows:
Supported functions:
Read Static files
When accessing the directory, you can automatically find the following index.html file. If there is no index.html, the file list is listed
MIME type Support
Cache support/control
Support gzip compression
Range support, breakpoint continued Pass
Global command execution
Subprocess running
1. Create a service to read static File
First introduce the http module, create a server, and listen to the configuration port:
const http = require('http'); const server = http.createServer(); // 监听请求 server.on('request', request.bind(this)); server.listen(config.port, () => { console.log(`静态文件服务启动成功, 访问localhost:${config.port}`); });
Write a fn to specifically handle requests and return static files. The url module obtains the path:
const url = require('url'); const fs = require('fs'); function request(req, res) { const { pathname } = url.parse(req.url); // 访问路径 const filepath = path.join(config.root, pathname); // 文件路径 fs.createReadStream(filepath).pipe(res); // 读取文件,并响应 }
Support searching for index.html:
if (pathname === '/') { const rootPath = path.join(config.root, 'index.html'); try{ const indexStat = fs.statSync(rootPath); if (indexStat) { filepath = rootPath; } } catch(e) { } }
When accessing the directory, list the file directory:
fs.stat(filepath, (err, stats) => { if (err) { res.end('not found'); return; } if (stats.isDirectory()) { let files = fs.readdirSync(filepath); files = files.map(file => ({ name: file, url: path.join(pathname, file) })); let html = this.list()({ title: pathname, files }); res.setHeader('Content-Type', 'text/html'); res.end(html); } }
html template:
function list() { let tmpl = fs.readFileSync(path.resolve(__dirname, 'template', 'list.html'), 'utf8'); return handlebars.compile(tmpl); }
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <meta http-equiv="X-UA-Compatible" content="ie=edge"> <title>{{title}}</title> </head> <body> <h1>hope-server静态文件服务器</h1> <ul> {{#each files}} <li> <a href={{url}}>{{name}}</a> </li> {{/each}} </ul> </body> </html>
2.MIME type support
Use the mime module to get the file type and set the encoding:
res.setHeader('Content-Type', mime.getType(filepath) + ';charset=utf-8');
3. Cache supports
http protocol cache:
Cache-Control: http1.1 content, tell customers How the client caches data, and the rules
private client can cache
public both the client and proxy server can cache
max-age=60 The cached content will expire after 60 seconds
no-cache needs to use the comparison cache to verify the data and force the source server to verify again
no-store All content will not be cached, and neither forced caching nor comparison caching will trigger
Expires: http1.0 content, cache- control will be overwritten and tell the client when the cache will expire
ETag: the hash value of the content. The next time the client requests, add if-none-match: etag value in the request header
Last-Modified : Last modified time, the next time the client requests, add if-modified-since: Last-Modified value in the request header
handleCache(req, res, stats, hash) { // 当资源过期时, 客户端发现上一次请求资源,服务器有发送Last-Modified, 则再次请求时带上if-modified-since const ifModifiedSince = req.headers['if-modified-since']; // 服务器发送了etag,客户端再次请求时用If-None-Match字段来询问是否过期 const ifNoneMatch = req.headers['if-none-match']; // http1.1内容 max-age=30 为强行缓存30秒 30秒内再次请求则用缓存 private 仅客户端缓存,代理服务器不可缓存 res.setHeader('Cache-Control', 'private,max-age=30'); // http1.0内容 作用与Cache-Control一致 告诉客户端什么时间,资源过期 优先级低于Cache-Control res.setHeader('Expires', new Date(Date.now() + 30 * 1000).toGMTString()); // 设置ETag 根据内容生成的hash res.setHeader('ETag', hash); // 设置Last-Modified 文件最后修改时间 const lastModified = stats.ctime.toGMTString(); res.setHeader('Last-Modified', lastModified); // 判断ETag是否过期 if (ifNoneMatch && ifNoneMatch != hash) { return false; } // 判断文件最后修改时间 if (ifModifiedSince && ifModifiedSince != lastModified) { return false; } // 如果存在且相等,走缓存304 if (ifNoneMatch || ifModifiedSince) { res.writeHead(304); res.end(); return true; } else { return false; } }
4. Compression
The client sends content through the request header Accept-Encoding: gzip, deflate tells the server which compression formats are supported, and the server compresses the content based on the supported compression formats. If the server does not support it, no compression will be performed.
getEncoding(req, res) { const acceptEncoding = req.headers['accept-encoding']; // gzip和deflate压缩 if (/\bgzip\b/.test(acceptEncoding)) { res.setHeader('Content-Encoding', 'gzip'); return zlib.createGzip(); } else if (/\bdeflate\b/.test(acceptEncoding)) { res.setHeader('Content-Encoding', 'deflate'); return zlib.createDeflate(); } else { return null; } }
5. Breakpoint resume transmission
The server uses the Range: bytes=0-xxx in the request header to determine whether it is making a Range request. If this value exists and is valid, it will only send Return the requested part of the file content, the response status code becomes 206, indicating Partial Content, and set Content-Range. If it is invalid, a 416 status code is returned, indicating that Request Range Not Satisfiable. If the Range request header is not included, continue to respond in the usual way.
getStream(req, res, filepath, statObj) { let start = 0; let end = statObj.size - 1; const range = req.headers['range']; if (range) { res.setHeader('Accept-Range', 'bytes'); res.statusCode = 206;//返回整个内容的一块 let result = range.match(/bytes=(\d*)-(\d*)/); if (result) { start = isNaN(result[1]) ? start : parseInt(result[1]); end = isNaN(result[2]) ? end : parseInt(result[2]) - 1; } } return fs.createReadStream(filepath, { start, end }); }
6. Global command execution
Achieved through npm link
Create a soft link for the npm package directory and link it to {prefix}/ lib/node_modules/
Create a soft link for the executable file (bin) and link it to {prefix}/bin/{name}
The npm link command makes the npm package command globally executable by linking directories and executable files.
Configuration in package.json
{ bin: { "hope-server": "bin/hope" } }
Create the bin directory hope file under the project, and use yargs to configure the command line to pass parameters
// 告诉电脑用node运行我的文件 #! /usr/bin/env node const yargs = require('yargs'); const init = require('../src/index.js'); const argv = yargs.option('d', { alias: 'root', demand: 'false', type: 'string', default: process.cwd(), description: '静态文件根目录' }).option('o', { alias: 'host', demand: 'false', default: 'localhost', type: 'string', description: '配置监听的主机' }).option('p', { alias: 'port', demand: 'false', type: 'number', default: 8080, description: '配置端口号' }).option('c', { alias: 'child', demand: 'false', type: 'boolean', default: false, description: '是否子进程运行' }) .usage('hope-server [options]') .example( 'hope-server -d / -p 9090 -o localhost', '在本机的9090端口上监听客户端的请求' ).help('h').argv; // 启动服务 init(argv);
7. Subprocess running
Achieved through spawn
index.js
const { spawn } = require('child_process'); const Server = require('./hope'); function init(argv) { // 如果配置为子进程开启服务 if (argv.child) { //子进程启动服务 const child = spawn('node', ['hope.js', JSON.stringify(argv)], { cwd: __dirname, detached: true, stdio: 'inherit' }); //后台运行 child.unref(); //退出主线程,让子线程单独运行 process.exit(0); } else { const server = new Server(argv); server.start(); } } module.exports = init; hope.js if (process.argv[2] && process.argv[2].startsWith('{')) { const argv = JSON.parse(process.argv[2]); const server = new Hope(argv); server.start(); }
8. Source code and testing
Source code address: hope-server
npm install hope-server -g
Enter any directory
hope-server
The above is what I compiled for everyone. I hope it will be helpful to everyone in the future.
Related articles:
How to implement string splicing in JS (extending String.prototype.format)
Using ES6 Solve the memory leak problem through WeakMap (detailed tutorial)
How to implement random switching code of WeChat ID through JavaScript (detailed tutorial)
The above is the detailed content of Sample code for actual node static file server. For more information, please follow other related articles on the PHP Chinese website!

Hot AI Tools

Undresser.AI Undress
AI-powered app for creating realistic nude photos

AI Clothes Remover
Online AI tool for removing clothes from photos.

Undress AI Tool
Undress images for free

Clothoff.io
AI clothes remover

AI Hentai Generator
Generate AI Hentai for free.

Hot Article

Hot Tools

Notepad++7.3.1
Easy-to-use and free code editor

SublimeText3 Chinese version
Chinese version, very easy to use

Zend Studio 13.0.1
Powerful PHP integrated development environment

Dreamweaver CS6
Visual web development tools

SublimeText3 Mac version
God-level code editing software (SublimeText3)

Hot Topics

Quark Netdisk and Baidu Netdisk are currently the most commonly used Netdisk software for storing files. If you want to save the files in Quark Netdisk to Baidu Netdisk, how do you do it? In this issue, the editor has compiled the tutorial steps for transferring files from Quark Network Disk computer to Baidu Network Disk. Let’s take a look at how to operate it. How to save Quark network disk files to Baidu network disk? To transfer files from Quark Network Disk to Baidu Network Disk, you first need to download the required files from Quark Network Disk, then select the target folder in the Baidu Network Disk client and open it. Then, drag and drop the files downloaded from Quark Cloud Disk into the folder opened by the Baidu Cloud Disk client, or use the upload function to add the files to Baidu Cloud Disk. Make sure to check whether the file was successfully transferred in Baidu Cloud Disk after the upload is completed. That's it

When deleting or decompressing a folder on your computer, sometimes a prompt dialog box "Error 0x80004005: Unspecified Error" will pop up. How should you solve this situation? There are actually many reasons why the error code 0x80004005 is prompted, but most of them are caused by viruses. We can re-register the dll to solve the problem. Below, the editor will explain to you the experience of handling the 0x80004005 error code. Some users are prompted with error code 0X80004005 when using their computers. The 0x80004005 error is mainly caused by the computer not correctly registering certain dynamic link library files, or by a firewall that does not allow HTTPS connections between the computer and the Internet. So how about

Recently, many netizens have asked the editor, what is the file hiberfil.sys? Can hiberfil.sys take up a lot of C drive space and be deleted? The editor can tell you that the hiberfil.sys file can be deleted. Let’s take a look at the details below. hiberfil.sys is a hidden file in the Windows system and also a system hibernation file. It is usually stored in the root directory of the C drive, and its size is equivalent to the size of the system's installed memory. This file is used when the computer is hibernated and contains the memory data of the current system so that it can be quickly restored to the previous state during recovery. Since its size is equal to the memory capacity, it may take up a larger amount of hard drive space. hiber

In network data transmission, IP proxy servers play an important role, helping users hide their real IP addresses, protect privacy, and improve access speeds. In this article, we will introduce the best practice guide on how to build an IP proxy server with PHP and provide specific code examples. What is an IP proxy server? An IP proxy server is an intermediate server located between the user and the target server. It acts as a transfer station between the user and the target server, forwarding the user's requests and responses. By using an IP proxy server

The role of a DHCP relay is to forward received DHCP packets to another DHCP server on the network, even if the two servers are on different subnets. By using a DHCP relay, you can deploy a centralized DHCP server in the network center and use it to dynamically assign IP addresses to all network subnets/VLANs. Dnsmasq is a commonly used DNS and DHCP protocol server that can be configured as a DHCP relay server to help manage dynamic host configurations in the network. In this article, we will show you how to configure dnsmasq as a DHCP relay server. Content Topics: Network Topology Configuring Static IP Addresses on a DHCP Relay D on a Centralized DHCP Server

A file path is a string used by the operating system to identify and locate a file or folder. In file paths, there are two common symbols separating paths, namely forward slash (/) and backslash (). These two symbols have different uses and meanings in different operating systems. The forward slash (/) is a commonly used path separator in Unix and Linux systems. On these systems, file paths start from the root directory (/) and are separated by forward slashes between each directory. For example, the path /home/user/Docume

What should I do if I can’t enter the game when the epic server is offline? This problem must have been encountered by many friends. When this prompt appears, the genuine game cannot be started. This problem is usually caused by interference from the network and security software. So how should it be solved? The editor of this issue will explain I would like to share the solution with you, I hope today’s software tutorial can help you solve the problem. What to do if the epic server cannot enter the game when it is offline: 1. It may be interfered by security software. Close the game platform and security software and then restart. 2. The second is that the network fluctuates too much. Try restarting the router to see if it works. If the conditions are OK, you can try to use the 5g mobile network to operate. 3. Then there may be more

In Linux systems, you can use the following command to view the contents of the log file: tail command: The tail command is used to display the content at the end of the log file. It is a common command to view the latest log information. tail [option] [file name] Commonly used options include: -n: Specify the number of lines to be displayed, the default is 10 lines. -f: Monitor the file content in real time and automatically display the new content when the file is updated. Example: tail-n20logfile.txt#Display the last 20 lines of the logfile.txt file tail-flogfile.txt#Monitor the updated content of the logfile.txt file in real time head command: The head command is used to display the beginning of the log file
