preference
v1.1.0
Published
Load various config files(`yaml`, `json`, `toml`, `ini`) and directory into one object. support Javascript(& Typescript).
Downloads
86
Maintainers
Readme
⚙️ Preference
Load various config files(yaml
, json
, toml
, ini
) and directory into one object. support Javascript(& Typescript).
Install
npm install preference --save
Usage
import library,
const preference = require("preference")
// or
import * as preference from "preference" // typescript
then, use like this:
// promise
preference.load("./your_config_directory").then(/* ... */)
await preference.load("./your_config_directory") // you can use promise by await
// sync
preference.loadSync("./your_config_directory")
Examples
Example with dotenv
.
Code
const path = require("path")
const dotenv = require("dotenv") // if you want to use dotenv
const preference = require("preference")
dotenv.config({
path: path.resolve(process.cwd(), "config/.env")
})
preference.load(path.resolve(process.cwd(), "config")).then(config => {
console.log(config) // output
})
Output
{
"cache": {
"default": {
"username": "cache",
"password": "cache123"
}
},
"client": {
"api": {
"host": "127.0.0.1",
"port": "8080",
"middleware": [
"cors",
"auth"
]
}
},
"database": {
"keyvalue": {
"host": "localhost",
"port": 6379
},
"master": {
"host": "localhost",
"username": "master",
"password": "master123"
},
"slave": {
"host": "slavehost",
"username": "slave",
"password": "slave123"
}
}
}
Support Formats
js
(built-in)json
(built-in)ini
,cfg
,conf
(requirenpm install ini --save
)yaml
(requirenpm install js-yaml --save
)toml
(requirenpm install toml --save
)
Configs
preference.create(/* preference.PreferenceConfig */)
option | type | default
-------------- | -------------------- | ------------------------------------------------
noIgnoreErrors | boolean | false
loaders | preference.Loader[] | [YamlLoader, JsonLoader, TomlLoader, IniLoader, JsLoader]
Custom Loader
const customLoader: preference.Loader = {
test(filename: string): boolean {
return /\.json$/i.test(filename)
},
async load(dirname: string): Promise<any> {
return {message: "load async", dirname}
},
loadSync(dirname: string): any {
return {message: "load sync", dirname}
},
}
const pref = preference.create({
loaders: [
customLoader,
new preference.YamlLoader(),
],
})