讓我們使用內建的 Bun.serve
API 來撰寫一個簡單的 HTTP 伺服器。首先,建立一個新的目錄。
mkdir quickstart
cd quickstart
執行 bun init
來建立一個新的專案。這是一個互動式工具;對於本教學,只需按下 enter
鍵接受每個提示的預設答案即可。
bun init
bun init helps you get started with a minimal project and tries to
guess sensible defaults. Press ^C anytime to quit.
package name (quickstart):
entry point (index.ts):
Done! A package.json file was saved in the current directory.
+ index.ts
+ .gitignore
+ tsconfig.json (for editor auto-complete)
+ README.md
To get started, run:
bun run index.ts
由於我們的進入點是一個 *.ts
檔案,因此 Bun 會為你產生一個 tsconfig.json
。如果你使用純 JavaScript,它會產生一個 jsconfig.json
。
執行一個檔案
開啟 index.ts
並貼上以下程式碼片段,它使用 Bun.serve
實作一個簡單的 HTTP 伺服器。
const server = Bun.serve({
port: 3000,
fetch(req) {
return new Response("Bun!");
},
});
console.log(`Listening on https://127.0.0.1:${server.port} ...`);
在 Bun
上看到 TypeScript 錯誤 ?
從你的 shell 中執行檔案。
bun index.ts
Listening on https://127.0.0.1:3000 ...
拜訪 https://127.0.0.1:3000 來測試伺服器。你應該會看到一個簡單的頁面,上面寫著「Bun!」。
執行一個腳本
Bun 也可以執行 package.json
中的 "scripts"
。新增以下腳本
{
"name": "quickstart",
"module": "index.ts",
"type": "module",
"scripts": {
"start": "bun run index.ts"
},
"devDependencies": {
"@types/bun": "^1.0.0"
}
}
然後使用 bun run start
來執行它。
bun run start
$ bun run index.ts
Listening on https://127.0.0.1:3000 ...
⚡️ 效能 — bun run
比 npm run
快大約 28 倍(6 毫秒對比 170 毫秒的開銷)。
安裝一個套件
讓我們透過安裝一個套件來讓我們的伺服器更有趣。首先安裝 figlet
套件及其型別宣告。Figlet 是將字串轉換為 ASCII 藝術的工具程式。
bun add figlet
bun add -d @types/figlet # TypeScript users only
更新 index.ts
以在 fetch
處理常式中使用 figlet
。
import figlet from "figlet";
const server = Bun.serve({
port: 3000,
fetch(req) {
const body = figlet.textSync("Bun!");
return new Response(body);
return new Response("Bun!");
},
});
重新啟動伺服器並重新整理頁面。你應該會看到一個新的 ASCII 藝術橫幅。
____ _
| __ ) _ _ _ __ | |
| _ \| | | | '_ \| |
| |_) | |_| | | | |_|
|____/ \__,_|_| |_(_)