Read configuration from a file Core
FileBind reads configuration values from a JSON, JSONC, or YAML file. The file is read once when FileBind.create() resolves. Element paths are resolved against the parsed file using nested keys first, falling back to flat dot-path keys.
Steps
1. Install the package if you haven't already:
npm install @config-bound/core2. Pass a FileBind to ConfigBound.createConfig:
import { ConfigBound, configItem, configSection } from "@config-bound/core";
import { FileBind } from "@config-bound/core/binds/file";
import { z } from "zod";
const config = await ConfigBound.createConfig(
{
port: configItem<number>({
default: 3000,
validator: z.number().int().min(1).max(65535)
}),
database: configSection({
host: configItem<string>({
default: "localhost",
validator: z.hostname()
})
})
},
{
binds: [await FileBind.create({ filePath: "./config.yaml" })]
}
);3. Write the config file:
# config.yaml
port: 8080
database:
host: db.production.localFileBind resolves filePath to an absolute path via path.resolve(), so relative paths are resolved from the current working directory at the time the bind is constructed.
Format detection
The format is inferred from the file extension. If your file uses a non-standard extension, pass format explicitly:
await FileBind.create({ filePath: "./settings.conf", format: "json" })| Extension | Inferred format |
|---|---|
.json | json |
.jsonc | jsonc |
.yml / .yaml | yaml |
Scope to a subtree with rootKey
If your config file contains multiple applications or a wrapper structure, use rootKey to scope the bind to a subtree:
# config.yaml
wrapper:
app:
port: 3000
database:
host: db.localawait FileBind.create({ filePath: "./config.yaml", rootKey: "wrapper" })
// "app.port" -> 3000
// "database.host" -> "db.local"Reload the file at runtime
The file is read once at creation. Call reload() to re-read it to pick up the latest file changes while the process is running:
const bind = await FileBind.create({ filePath: "./config.yaml" });
// ...later, after the file changes:
await bind.reload();Null handling
Explicit null values in the file are treated as unset. The next bind in the priority order, or the element's default, takes over.
Related
FileBindAPI reference- Use EnvVarBind - read config from environment variables
- Use StaticBind - supply config values directly in code