【管子先生的Node之旅·19】实现简单的静态文件托管

2017-11-03  本文已影响0人  管子先生
images.png
我们来简单的实现一下静态文件托管
  1. 先来构建一个基础服务器
//引入相关模块
const http = require('http'),
    fs = require('fs');
//创建服务器
const serv = http.createServer((req, res) => {
  //...
});
//监听
serv.listen(3000);
  1. 对路由进行判断,如果不存在路径上则返回404
  //是否为GET请求及
    if (req.method == "GET") {
        //检查是否为/images路径下的png文件(此例子只对png文件处理)
        if (req.url.substr(0, 7) == "/images" && req.url.substr(-4) == '.png') {
           
        } else if (req.url == '/') {

        } else {
            res.writeHead(404, { 'Content-Type': 'text/html;charset=utf-8' });
            res.end('<h1>当前页面不存在!</h1>');
        }
    }
  1. 对请求文件进行判断,没则返回空
fs.stat(__dirname + req.url, (err, stat) => {
    if (err || !stat.isFile()) {
        res.writeHead(404);
        res.end('文件不存在');
        return;
    }
});
  1. 对文件进行处理,并输出
// 文件处理
function serve(path, type) {
    res.writeHead(200, { 'Content-Type': type });
    //文件读取,并输出文件
    fs.createReadStream(path).pipe(res);
}
  1. 组合起来
//引入相关模块
const http = require('http'),
    fs = require('fs');
//创建服务器
const serv = http.createServer((req, res) => {
    //是否为GET请求及
    if (req.method == "GET") {
        //检查是否时/images路径下的
        if (req.url.substr(0, 7) == "/images" && req.url.substr(-4) == '.png') {
            fs.stat(__dirname + req.url, (err, stat) => {
                if (err || !stat.isFile()) {
                    res.writeHead(404, { 'Content-Type': 'text/html;charset=utf-8' });
                    res.end('<h1>当前文件不存在!</h1>');
                    return;
                }
                serve(__dirname + req.url, "image/png");
            });
        } else if (req.url == '/') {
            serve(__dirname + '/index.html', 'text/html');
        } else {
            res.writeHead(404, { 'Content-Type': 'text/html;charset=utf-8' });
            res.end('<h1>当前页面不存在!</h1>');
        }
    }
    // 文件处理
    function serve(path, type) {
        res.writeHead(200, { 'Content-Type': type });
        //文件读取,并输出文件
        fs.createReadStream(path).pipe(res);
    }
});
//监听
serv.listen(3000);
上一篇 下一篇

猜你喜欢

热点阅读