静态资源 读取方法

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('服务器启动成功...');
原文地址:https://www.cnblogs.com/ericblog1992/p/13085356.html