Runtime APIs
Read environment variables and arguments
Read configuration from environment files and accept command-line arguments without hard-coding changing values.
8 minute lesson
Applications need values that change between machines. Ports, database paths, and API tokens do not belong in source code.
Bun automatically reads .env files. Create .env in the project root:
PORT=3000
DATABASE_PATH=notes.sqlite
Read those values through Bun.env:
const port = Number(Bun.env.PORT ?? 3000)
const databasePath = Bun.env.DATABASE_PATH ?? 'notes.sqlite'
console.log({ port, databasePath })
Bun.env contains strings or undefined. Convert numbers and validate required values before using them.
Do not commit secrets in .env. Add the file to .gitignore, and provide an .env.example containing safe placeholder names instead.
Read command-line arguments
Command-line arguments are useful for small tools and maintenance tasks.
Create greet.ts:
const name = Bun.argv[2] ?? 'friend'
console.log(`Hello ${name}`)
Pass the name after the file:
bun greet.ts Flavio
The output is:
Hello Flavio
The first two entries in Bun.argv identify the Bun executable and the script. Your first argument starts at index 2.
Environment variables configure how an application runs. Arguments describe what one execution should do. Keeping those roles separate makes commands easier to understand.
Lesson completed