In modern web design, whether it is a personal website or a corporate website, a large number of image resources are needed. Therefore, how to efficiently store and distribute these image resources has become one of the problems that many website administrators or developers need to face. In this case, an efficient image server can solve the problem. This article will introduce how to use nodejs to build an efficient image server.
- Implementing a simple web server
Nodejs is an event-driven JavaScript runtime environment that can build web applications quickly and scalably. In this article, we will use Nodejs’s http module to create a simple web server.
We can create a simple Web server through the following code:
const http = require('http'); const server = http.createServer((req, res) => { res.writeHead(200, {'Content-Type': 'text/plain'}); res.write('Hello World!'); res.end(); }); server.listen(3000, () => { console.log('Server running at http://localhost:3000/'); });
The above code uses the createServer() method in the http module to create a Web server. When a client connects When the server is reached, the server will send the "Hello World!" string to the client, where it will exist on the client until the server terminates.
- Implementing a picture server
For a picture server, we need to modify the above code and add some specific functions to process and distribute pictures.
const http = require('http'); const fs = require('fs'); const path = require('path'); const server = http.createServer((req, res) => { // 获取请求文件的后缀名 const extname = path.extname(req.url); // 如果后缀名是.jpg或.png if (extname === '.jpg' || extname === '.png') { // 读取文件 fs.readFile('./images' + req.url, (err, data) => { if (err) { // 文件不存在,返回404错误 res.writeHead(404, {'Content-Type': 'text/plain'}); res.write('404 Not Found'); res.end(); } else { // 返回文件内容 res.writeHead(200, {'Content-Type': 'image/jpeg'}); res.write(data); res.end(); } }); } else { // 请求的不是图片,返回404错误 res.writeHead(404, {'Content-Type': 'text/plain'}); res.write('404 Not Found'); res.end(); } }); server.listen(3000, () => { console.log('Server running at http://localhost:3000/'); });
The above code uses the fs module in Nodejs to read the image file in the specified directory, and then returns the binary data of the file to the client. If a non-image resource is requested, a 404 error will be returned.
- Performance Optimization of Image Server
In order to improve the performance of the image server, we can use the caching mechanism in Nodejs to reduce the number of file I/O operations, thereby increasing access speed.
The following is a simple cache implementation:
const http = require('http'); const fs = require('fs'); const path = require('path'); const LRU = require('lru-cache'); const cacheOptions = { max: 500, // 最多缓存500个对象 length: (n, key) => n * 2 + key.length, // 缓存对象的大小 dispose: (key, n) => n.close(), // 执行垃圾回收 maxAge: 1000 * 60 * 60 // 缓存1小时 }; const imgCache = new LRU(cacheOptions); const server = http.createServer((req, res) => { // 获取请求文件的后缀名 const extname = path.extname(req.url); // 如果后缀名是.jpg或.png if (extname === '.jpg' || extname === '.png') { // 检查缓存中是否已经有该文件的缓存 const imgData = imgCache.get(req.url); if (imgData) { // 直接从缓存中返回文件的二进制数据 res.writeHead(200, {'Content-Type': `image/${extname.slice(1)}`}); res.write(imgData, 'binary'); res.end(); } else { // 如果缓存中没有该文件的缓存,则读取文件并将其添加到缓存中 fs.readFile('./images' + req.url, 'binary', (err, data) => { if (err) { // 文件不存在,返回404错误 res.writeHead(404, {'Content-Type': 'text/plain'}); res.write('404 Not Found'); res.end(); } else { // 返回文件内容 res.writeHead(200, {'Content-Type': `image/${extname.slice(1)}`}); res.write(data, 'binary'); res.end(); // 将文件数据添加到缓存中 imgCache.set(req.url, data); } }); } } else { // 请求的不是图片,返回404错误 res.writeHead(404, {'Content-Type': 'text/plain'}); res.write('404 Not Found'); res.end(); } }); server.listen(3000, () => { console.log('Server running at http://localhost:3000/'); });
The above code uses the LRU cache in Nodejs to cache the binary data of the image file. In this way, when multiple clients request the same image, the server only needs to read the image file once and add it to the cache, and read it directly from the cache in subsequent requests, thus greatly reducing file I/O. The number of operations increases the access speed.
- Deploy and run the image server
To deploy and run the image server, you need to install nodejs and npm first, and then execute the following commands:
npm init npm install http fs path lru-cache --save node server.js
Among them, the npm init command will Generate a package.json file, the npm install command will download the required dependent libraries for installation, and the node server.js command will run the image server.
It should be noted that in an actual production environment, images or other static resources need to be stored in independent storage devices or CDN nodes to improve the access speed and availability of images.
Summary:
This article introduces how to use nodejs to build an efficient image server, and provides some performance optimization methods. Hope it helps developers.
The above is the detailed content of Nodejs builds image server. For more information, please follow other related articles on the PHP Chinese website!

The article discusses useEffect in React, a hook for managing side effects like data fetching and DOM manipulation in functional components. It explains usage, common side effects, and cleanup to prevent issues like memory leaks.

Lazy loading delays loading of content until needed, improving web performance and user experience by reducing initial load times and server load.

The article discusses currying in JavaScript, a technique transforming multi-argument functions into single-argument function sequences. It explores currying's implementation, benefits like partial application, and practical uses, enhancing code read

Higher-order functions in JavaScript enhance code conciseness, reusability, modularity, and performance through abstraction, common patterns, and optimization techniques.

The article explains React's reconciliation algorithm, which efficiently updates the DOM by comparing Virtual DOM trees. It discusses performance benefits, optimization techniques, and impacts on user experience.Character count: 159

The article explains useContext in React, which simplifies state management by avoiding prop drilling. It discusses benefits like centralized state and performance improvements through reduced re-renders.

Article discusses preventing default behavior in event handlers using preventDefault() method, its benefits like enhanced user experience, and potential issues like accessibility concerns.

Redux reducers are pure functions that update the application's state based on actions, ensuring predictability and immutability.


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

SublimeText3 Chinese version
Chinese version, very easy to use

mPDF
mPDF is a PHP library that can generate PDF files from UTF-8 encoded HTML. The original author, Ian Back, wrote mPDF to output PDF files "on the fly" from his website and handle different languages. It is slower than original scripts like HTML2FPDF and produces larger files when using Unicode fonts, but supports CSS styles etc. and has a lot of enhancements. Supports almost all languages, including RTL (Arabic and Hebrew) and CJK (Chinese, Japanese and Korean). Supports nested block-level elements (such as P, DIV),

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

DVWA
Damn Vulnerable Web App (DVWA) is a PHP/MySQL web application that is very vulnerable. Its main goals are to be an aid for security professionals to test their skills and tools in a legal environment, to help web developers better understand the process of securing web applications, and to help teachers/students teach/learn in a classroom environment Web application security. The goal of DVWA is to practice some of the most common web vulnerabilities through a simple and straightforward interface, with varying degrees of difficulty. Please note that this software

SecLists
SecLists is the ultimate security tester's companion. It is a collection of various types of lists that are frequently used during security assessments, all in one place. SecLists helps make security testing more efficient and productive by conveniently providing all the lists a security tester might need. List types include usernames, passwords, URLs, fuzzing payloads, sensitive data patterns, web shells, and more. The tester can simply pull this repository onto a new test machine and he will have access to every type of list he needs.
