讓我們使用內建的 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": "latest"
}
}
然後使用 bun run start
執行它。
bun run start
$ bun run index.ts
Listening on https://127.0.0.1:3000 ...
⚡️ 效能 — bun run
大約比 npm run
快 28 倍(6 毫秒 vs 170 毫秒的 overhead)。
安裝套件
讓我們透過安裝套件,讓我們的伺服器更有趣一點。首先安裝 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 藝術橫幅。
____ _
| __ ) _ _ _ __ | |
| _ \| | | | '_ \| |
| |_) | |_| | | | |_|
|____/ \__,_|_| |_(_)