Logo of rc9

rc9

读写配置从未如此简单!

读写配置从未如此简单!

安装

使用 npm 或 yarn 安装

npm i rc9
# or
yarn add rc9

导入到您的 Node.js 项目

// CommonJS
const { read, write, update } = require('rc9')

// ESM
import { read, write, update } from 'rc9'

用法

.conf:

db.username=db username
db.password=db pass
db.enabled=true

更新配置

update({ 'db.enabled': true }) // or update(..., { name: '.conf' })

推送到数组

update({ 'modules[]': 'test' })

读取/写入配置

const config = read() // or read('.conf')

// config = {
//   db: {
//     username: 'db username',
//     password: 'db pass',
//     enabled: true
//   }
// }

config.enabled = false
write(config) // or write(config, '.conf')

用户配置

通常将配置保存在用户主目录中 (MacOS: /Users/{name}, Linux: /home/{name}, Windows: C:\users\{name})

您可以使用 readUser/writeuser/updateUser 快捷方式来快速完成此操作

writeUser({ token: 123 }, '.zoorc') // Will be saved in {home}/.zoorc

const conf = readUser('.zoorc') // { token: 123 }

取消扁平化

RC 在写入和读取 rcfile 时,使用 flat 自动进行扁平化/取消扁平化。

这意味着您可以使用 . 作为键来定义对象。一些示例:

  • hello.world = true <=> { hello: { world: true }
  • test.0 = A <=> tags: [ 'A' ]

注意: 如果您使用可以覆盖的键,例如 x=x.y=,您可以通过传递 flat: true 选项来禁用此功能。

提示: 您可以使用以 [] 结尾的键来推送到数组,例如 test[]=A

原生值

RC 使用 destr 将值转换为原生 JavaScript 值。

因此,读取 count=123 会得到 { count: 123 }(而不是 { count: "123" }),如果您想保留字符串原样,可以使用 count="123"

导出

const defaults: RCOptions;
function parse(contents: string, options?: RCOptions): RC
function parseFile(path: string, options?: RCOptions): RC
function read(options?: RCOptions | string): RC;
function readUser(options?: RCOptions | string): RC;
function serialize(config: RC): string;
function write(config: RC, options?: RCOptions | string): void;
function writeUser(config: RC, options?: RCOptions | string): void;
function update(config: RC, options?: RCOptions | string): RC;
function updateUser(config: RC, options?: RCOptions | string): RC;

类型

type RC = Record<string, any>;
interface RCOptions {
    name?: string;
    dir?: string;
    flat?: boolean;
}

默认值

{
  name: '.conf',
  dir: process.cwd(),
  flat: false
}

为什么是 RC9?

第一个猜猜看吧 🐇

许可

MIT。倾情打造 💖