preference
TypeScript icon, indicating that this package has built-in type declarations

1.1.0 • Public • Published

⚙️ Preference

Build Downloads Version License

NPM

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.

Example Directory

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 (require npm install ini --save)
  • yaml (require npm install js-yaml --save)
  • toml (require npm 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(),
  ],
})

Package Sidebar

Install

npm i preference

Weekly Downloads

23

Version

1.1.0

License

MIT

Unpacked Size

60.2 kB

Total Files

60

Last publish

Collaborators

  • wan2land