zoukankan      html  css  js  c++  java
  • 静态资源 读取方法

    inpm install mime
    const mime = require('mime');
    指定返回资源的类型
    mime  可以自动区分页面文件
     
    const http = require('http');
    const url = require('url');
    const app = http.createServer();
    const path = require('path');
    const fs = require('fs');
    const mime = require('mime');


    app.on('request', (req, res) => {

        // 获取用户请求的路径
        let pathname = url.parse(req.url).pathname;
        pathname = pathname == '/' ? '/default.html' : pathname;
        // 将用户的请求路径转换成实际的服务器硬盘
        let realPath = path.join(__dirname, 'public', pathname);
        // 返回资源的类型
        let type = mime.getType(realPath);

        // 读取文件
        fs.readFile(realPath, (error, result) => {
            // 如果文件读取失败
            if (error != null) {
                // 设置读取字符集
                res.writeHead(404, {
                    'content-type': 'text/plain;charset=utf8'
                });
                res.end('文件读取失败');
                return;
            }
            // 指定返回资源的类型
            res.writeHead(200, {
                'content-type': type
            });

            res.end(result);
        });
    });

    app.listen(3000);
    console.log('服务器启动成功...');
  • 相关阅读:
    docker 的使用
    WEB应用支持RESTFUL风格方法
    tomcat7 安装 windows 服务
    获取POM.XML依赖的JAR包
    集成 dubbo 微服务
    linux 修改yum 为阿里云源
    poj3904
    2013 ACM/ICPC 长春网络赛E题
    2013 ACM/ICPC 长春网络赛F题
    2013 ACM/ICPC 长沙网络赛J题
  • 原文地址:https://www.cnblogs.com/ericblog1992/p/13085356.html
Copyright © 2011-2022 走看看