bun替代nginx,做文件服务器

48 阅读1分钟

通过实现部分nginx功能,掌握bun的高级用法

  • Setp0: 确保bun已经正确安装
$ bun -v

1.3.4

如果还未安装,请到B站看下我的安装视频:bun win11 安装 bun linux 安装

  • Setp1: 建立bun脚手架项目bun-nginx
$ bun init bun-nginx

? Select a project template - Press return to submit.
❯ Blank
  React
  Library

✓ Select a project template: Blank

 + .gitignore
 + CLAUDE.md
 + .cursor/rules/use-bun-instead-of-node-vite-npm-pnpm.mdc -> CLAUDE.md
 + index.ts
 + tsconfig.json (for editor autocomplete)
 + README.md
  • Setp2: 改成js项目(本文使用js示例)
  1. 将index.ts重命名为nginx.js
  2. package.json 的module 改为 nginx.js
//新建html文件夹,配置root目录
const config = {
    "root" : "D:\\js\\bun\\bun-nginx\\html"
}

// 生成随机id
// Math是bun内置函数
const id = Math.random().toString(36).slice(2);

const server = Bun.serve({
    port: 80,
    idleTimeout: 10,
    // 开启reusePort,多个进程共享端口, 注意:只支持linux
    reusePort: false,
    //试用fetch函数,可以拿到request对象
    async fetch(req) {
        // 解析url路径
        const path = decodeURIComponent(new URL(req.url).pathname);
        console.log(`${id} ${req.method} ${path}`);
        // respond with text/html
        if (path === "/") return new Response("Welcome to Bun!");

        try {
            const _file = Bun.file(`${config.root}/${path}`);
            // 检查文件是否存在
            if (!await _file.exists()) {
                throw new Error("File not found");
            }
            return new Response(_file);
        } catch (error) {
            console.log(error);
            return new Response("Page not found", { status: 404 });
        }
        
    },
});

console.log(`Listening on ${server.url}`);
  • Setp3: 启动测试
$ bun run src\nginx.js

Listening on http://localhost/
  • 在root目录放入任意类型文件。
  • 在浏览器中输入http://localhost/文件名 如果是html,mp4等浏览器认识的文件类型,浏览器会 直接展示;如果是zip等文件类型,会直接下载。