• 静态资源 读取方法


    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('服务器启动成功...');
  • 相关阅读:
    P4611 [COCI2011-2012#7] TRAMPOLIN
    P3119 [USACO15JAN]草鉴定Grass Cownoisseur
    P4417 [COCI2006-2007#2] STOL
    P4645 [COCI2006-2007 Contest#3] BICIKLI
    P1155 双栈排序
    P4610 [COCI2011-2012#7] KAMPANJA
    P4329 [COCI2006-2007#1] Bond
    EZOJ #227
    EZOJ #226
    p4980 polya定理
  • 原文地址:https://www.cnblogs.com/ericblog1992/p/13085356.html
Copyright © 2020-2023  润新知