⚙️ 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")
import * as preference from "preference"
then, use like this:
preference.load("./your_config_directory").then()
await preference.load("./your_config_directory")
preference.loadSync("./your_config_directory")
Examples
Example with dotenv
.
Example Directory
Code
const path = require("path")
const dotenv = require("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
{
"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
(require npm install ini --save
)
yaml
(require npm install js-yaml --save
)
toml
(require npm install toml --save
)
Configs
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(),
],
})