node.js 写一个静态目录做cdn

/*
 * @Author: HuangBingQuan <17671241237@163.com>
 * @Date: 2024-07-07 21:16:08
 * @LastEditTime: 2024-07-08 12:56:45
 * @FilePath: /myCdn/index.js
 */
const http = require('http');
const fs = require('fs');
const URL = require('url');
const path = require('path');

const PORT = 1024;

// 得到文件的状态
async function getStat(filename) {
    try {
        return await fs.promises.stat(filename);
    }catch {
        console.log('catch.....');
        return null;
    }
}

/**
 * 得到要处理的文件内容
 */
async function getFileInfo(url) {
    const urlObj = URL.parse(url);
    // 要处理的文件路径
    let filename = path.resolve(__dirname, urlObj.pathname.substring(1));
    let stat = await getStat(filename);
    if(!stat) {
        console.log("文件不存在");
        return null;
    }else if(stat.isDirectory()) {
        filename = path.resolve(__dirname, urlObj.pathname.substring(1), 'index.html');
        stat = await getStat(filename);
        if(!stat) {
            console.log("文件不存在");
            return null;
        }else {
            console.log(filename);
            return await fs.promises.readFile(filename);
        }
    }else {
        console.log("正常文件");
        return await fs.promises.readFile(filename);
    }
    console.log("stat", stat);
}

const handler = async (req, res)=> {
    const info = await getFileInfo(req.url);
    if(info) {
        res.write(info);
    }else {
        res.statusCode = 404;
        res.write("Resource is not exits");
    }
    res.end();
}

const server = http.createServer(handler);

server.on('listening', ()=> {
    console.log(`server listen ${PORT}`);
});

server.listen(PORT);
posted @ 2024-07-08 13:11  HuangBingQuan  阅读(9)  评论(0编辑  收藏  举报