Node.js 基础篇(十二):搭建一个简单的静态资源服务

在这里插入图片描述

server.js

const http = require('http')
const path = require('path')
const fs = require('fs')
const mime = require('mime') // 用来表示文档、文件或字节流的性质和格式 https://developer.mozilla.org/zh-CN/docs/Web/HTTP/Basics_of_HTTP/MIME_types

const server = http.createServer((request, response) => {
    
    
  const urlStr = request.url
  const ext = path.parse(urlStr).ext // 获取文件后缀
  const contentType = mime.getType(ext) || 'text/html' // 用后缀来判断服务端响应数据类型

  const file = path.join(__dirname, '/static', urlStr) // 获取请求文件在硬盘中静态资源(static)的物理路径
  const indexHtmlFile = path.join(__dirname, '/static', 'index.html') // 获取index.html在硬盘中静态资源(static)的物理路径
  if (fs.existsSync(file)) {
    
     // 判断该文件或文件夹是否存在
    // 判断是文件还是文件夹
    if (fs.statSync(file).isFile()) {
    
     // 是文件,则读取并返回该文件
      fs.readFile(file, (err, data) => {
    
    
        if (err) {
    
    
          console.log(err);
          response.writeHead(404, {
    
     'Content-Type': `${
      
      contentType}; charset=utf-8`})
          response.end(err)
        } else {
    
    
          response.writeHead(200, {
    
     'Content-Type': `${
      
      contentType}; charset=utf-8`})
          response.end(data)
        }
      })
    } else {
    
      // 是文件夹,则默认读取目录下的index.html
      fs.readFile(indexHtmlFile, (err, data) => {
    
    
        if (err) {
    
    
          console.log(err);
          response.writeHead(404, {
    
     'Content-Type': `${
      
      contentType}; charset=utf-8`})
          response.end(err)
        } else {
    
    
          response.writeHead(200, {
    
     'Content-Type': `${
      
      contentType}; charset=utf-8`})
          response.end(data)
        }
      })
    }
  } else {
    
     // url查找的文件或文件夹不存在,响应404
    response.writeHead(404, {
    
     'Content-Type': `${
      
      contentType}; charset=utf-8`})
    response.end('file or folder not found.')
  }
})

server.listen(8080, () => {
    
    
  console.log('localhost:8080');
})

静态资源目录
在这里插入图片描述


index.html

<!doctype html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <meta name="viewport"
        content="width=device-width, user-scalable=no, initial-scale=1.0, maximum-scale=1.0, minimum-scale=1.0">
  <meta http-equiv="X-UA-Compatible" content="ie=edge">
  <title>Document</title>
  <link rel="stylesheet" href="./styles/normal.css">
</head>
<body>
<h1>这是一个静态资源服务</h1>
<img src="./images/lb.jpeg" alt="">
<script src="./js/common/utils.js"></script>
<script src="./js/todo.js"></script>
</body>
</html>

服务运行结果如下
在这里插入图片描述


源码:https://gitee.com/yanhuakang/nodejs-demos/tree/master/codes/basics/09-StaticResourceService

猜你喜欢

转载自blog.csdn.net/qq_41887214/article/details/122959562