Neon 是一個完全託管的無伺服器 Postgres。Neon 分離了計算和儲存,提供了自動擴充套件、分支、無底儲存等現代開發人員功能。
透過建立一個專案目錄,使用 bun init 初始化目錄,並將 Neon serverless driver 新增為專案依賴項來開始。
mkdir bun-neon-postgrescd bun-neon-postgresbun init -ybun add @neondatabase/serverless建立一個 .env.local 檔案,並將你的 Neon Postgres 連線字串 新增到其中。
DATABASE_URL=postgresql://username:password@ep-adj-noun-guid.us-east-1.aws.neon.tech/neondb?sslmode=require
將以下程式碼貼上到你的專案的 index.ts 檔案中。
import { neon } from "@neondatabase/serverless";
// Bun automatically loads the DATABASE_URL from .env.local
// Refer to: https://bun.nodejs.com.tw/docs/runtime/env for more information
const sql = neon(process.env.DATABASE_URL);
const rows = await sql`SELECT version()`;
console.log(rows[0].version);
使用 bun ./index.ts 啟動程式。Postgres 版本將列印到控制檯。
bun ./index.tsPostgreSQL 16.2 on x86_64-pc-linux-gnu, compiled by gcc (Debian 10.2.1-6) 10.2.1 20210110, 64-bit此示例使用了 Neon serverless driver 的 SQL-over-HTTP 功能。Neon 的 serverless driver 還公開了 Client 和 Pool 建構函式,以支援會話、互動式事務和 node-postgres 相容性。
有關 serverless driver 的完整概述,請參閱 Neon 的文件。