21xrx.com
2025-03-27 06:59:55 Thursday
文章检索 我的文章 写文章
Node.js静态资源服务器
2023-07-03 22:29:20 深夜i     --     --
Node js 静态资源 服务器

Node.js是一种非常流行的后端JavaScript运行环境,它可以用来构建高性能、可扩展的Web应用程序。在Web应用程序的开发过程中,有许多要素需要考虑,其中最重要的一项是如何提供静态资源。

静态资源包括HTML、CSS、JavaScript、图像和音频文件等,它们不需要任何动态处理即可发送到客户端,因此它们的处理方式与Node.js服务器上的其他请求不同。为此,Node.js提供了一个用于托管静态资源的内置模块,称为“静态资源服务器”。

一个简单的Node.js静态资源服务器可以使用以下代码实现:

const http = require('http');
const fs = require('fs');
const path = require('path');
const hostname = '127.0.0.1';
const port = 3000;
const server = http.createServer((req, res) => {
  let filePath = '.' + req.url;
  if (filePath == './')
    filePath = './index.html';
  
  const extname = String(path.extname(filePath)).toLowerCase();
  const mimeTypes = {
    '.html': 'text/html',
    '.js': 'text/javascript',
    '.css': 'text/css',
    '.json': 'application/json',
    '.png': 'image/png',
    '.jpg': 'image/jpg',
    '.gif': 'image/gif',
    '.svg': 'image/svg+xml',
    '.wav': 'audio/wav',
    '.mp4': 'video/mp4',
    '.woff': 'application/font-woff',
    '.ttf': 'application/font-ttf',
    '.eot': 'application/vnd.ms-fontobject',
    '.otf': 'application/font-otf',
    '.wasm': 'application/wasm'
  };
  const contentType = mimeTypes[extname] || 'application/octet-stream';
  fs.readFile(filePath, function(error, content) {
    if (error) {
      if (error.code == 'ENOENT') {
        fs.readFile('./404.html', function(error, content) {
          res.writeHead(404, { 'Content-Type': 'text/html' });
          res.end(content, 'utf-8');
        });
      } else {
        res.writeHead(500);
        res.end('Sorry, check with the site admin for error: ' + error.code + ' ..\n');
        res.end();
      }
    } else {
      res.writeHead(200, { 'Content-Type': contentType });
      res.end(content, 'utf-8');
    }
  });
});
server.listen(port, hostname, () => {
  console.log(`Server running at http://${hostname}:${port}/`);
});

在此代码中,我们创建了一个HTTP服务器,并使用fs模块和path模块来读取请求的文件并确定文件类型。我们还在mimeTypes对象中包含了所有可能的文件扩展名及其MIME类型。如果访问的文件不存在,服务器将发送一个404错误。如果存在其他错误,则会发送一个500错误。

使用以上代码,我们可以在本地主机的端口3000上运行自己的Node.js静态资源服务器。要托管静态资源,只需将它们放在服务器的根目录下,然后使用合适的文件路径进行访问。

总之,Node.js静态资源服务器使托管静态资源变得更加简单和高效。它是通过提供适当的MIME类型来发送文件,确保它们正确地在客户端呈现。

  
  

评论区