Home  >  Article  >  Web Front-end  >  Nodejs builds image server

Nodejs builds image server

王林
王林Original
2023-05-16 20:29:06803browse

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.

  1. 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.

  1. 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.

  1. 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.

  1. 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!

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