Node.js-综合案例-静态文件服务器

本文详细介绍如何使用Node.js创建一个静态文件服务器,包括处理URL、设置默认文件、获取文件后缀并配置content-type、错误处理及返回404页面。通过具体步骤和代码示例,帮助读者理解服务器工作原理。

10. 静态文件服务器

例子:

(1)创建http服务

(2)访问拼接文件

(3)规范url

(4)获取文件的后缀,设置不同的content-type

(5)404页面

(6)处理请求的url只保留路径和文件,去掉url后缀

// 导入模块
const http = require('http');
const fs = require('fs');
const url = require('url');
const path = require('path');
// 1.创建http服务
http.createServer(function (req,res) {
    // console.log(req.url);
    // 处理请求的url只保留路径和文件,去掉url访问的后缀
    let pathname = url.parse(req.url).pathname;
    console.log(pathname);
    // 6.把index.html设置为每个目录默认打开的文件
    if(pathname.indexOf('.') === -1){
        pathname = path.join(pathname,'index.html')
    }
    console.log(pathname);
    // 2.访问目录前加上htdocs文件夹,拼接文件名
    // 3.path.normalize()规范url,以防恶意多字符htdocs//////zhang
    let fileurl = path.normalize(path.join('../htdocs',pathname));
    console.log(fileurl);//htdocs\zhang

    //4. 获取文件的后缀,设置不同的content-type
    let extname = path.extname(fileurl);
    console.log(extname);
    // 5.如果访问的文件不存在,加载404页面
    // 读取文件
    fs.readFile(fileurl,function (err,data) {
        if(err){

            fs.readFile('../htdocs/404.html',function (err,data) {
                if (err) throw err;
                res.writeHead(404,{'Content-type':'text/html;charset=utf8'});
                res.end(data);
            })
            return;
        }
        //根据不同的文件后缀设置不同的content-type
        // switch (extname){
        //     case '.html':contentType = 'text/html;charset=utf8';
        //     case '.css'.....
        // }
        // 以上判断文件后缀,设置格式,由于太多,所以引入json文件
        // 读取mime.json
        fs.readFile('mime.json',function (err,mimeData) {
            if (err) throw err;
            console.log(JSON.parse(mimeData));
            let mimeList = JSON.parse(mimeData);//处理json数据
            let contentType = mimeList[extname] || 'text/plain';//根据扩展名获取contentType
            // 设置响应头
            res.writeHead(200,{'Content-type':contentType});
            // 结束响应
            res.end(data);
        });
    });
}).listen(8002,function () {
    console.log('http server is runing on port 8002');
});

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值