Home > Article > Web Front-end > Nodejs builds image server
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.
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.
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.
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.
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!