config-anchor
v0.1.0
Published
JSON5 config locator and reader/writer for local tools
Maintainers
Readme
config-anchor
config-anchor 是一个面向本地工具的 JSON5 配置定位与读写库。
它的核心目标很简单:先定义配置文件应该去哪里找,再用一套小而稳定的 API 读取和更新这个配置文件。
安装
npm install config-anchor基本用法
const { createAnchor } = require('config-anchor');
const anchor = createAnchor({
name: 'demo-app',
fileName: 'config.json5',
search: ['upward', 'xdg', 'home']
});
// anchor 是一个 ConfigAnchor 实例
const config = await anchor.read();
const port = await anchor.get('server.port', 3000);
await anchor.update(draft => {
draft.server = draft.server || {};
draft.server.port = 8080;
delete draft.server.host;
});import { createAnchor } from 'config-anchor';
type AppConfig = {
server?: {
port?: number;
host?: string;
};
};
const anchor = createAnchor<AppConfig>({
fileName: 'config.json5',
search: ['upward', 'xdg', 'home']
});
// anchor 是一个 ConfigAnchor<AppConfig> 实例
const config = await anchor.read();
const port = config.server?.port;路径解析
你可以传入固定路径,也可以传入搜索策略。
const anchor = createAnchor({
path: './config/local.json5'
});const anchor = createAnchor({
name: 'demo-app',
fileName: 'config.json5',
search: ['upward', 'xdg', 'home']
});推荐搜索模式
当配置应该在一个项目目录树内共享时,优先使用 upward:
const anchor = createAnchor({
fileName: 'config.json5',
search: ['upward', 'home']
});它特别适合这些场景:
- monorepo
- 从子目录启动的 CLI
- 在嵌套目录中运行的脚本
在这种配置下,config-anchor 会按下面的顺序查找:
- 当前工作目录
- 当前目录的父目录
- 更上一级父目录
- 一直向上查到文件系统根目录
- 如果仍未找到,则回退到
cwd/config.json5
如果你希望优先使用项目内配置,其次使用用户级配置,可以把 upward 和 xdg / home 组合起来:
const anchor = createAnchor({
name: 'demo-app',
fileName: 'config.json5',
search: ['upward', 'xdg', 'home']
});支持的搜索项:
cwdupwardhomexdgsource{ type: 'path', value: './relative/or/absolute/path.json5' }
其中:
xdg会解析到$XDG_CONFIG_HOME/<name>/<fileName>,如果XDG_CONFIG_HOME未设置,则退回到~/.config/<name>/<fileName>upward会从cwd开始逐级向父目录查找,直到找到<fileName>
如果配置的搜索位置都不存在,并且 search 中包含 cwd 或 upward,则最终会回退到 cwd 对应的目标路径。
API
createAnchor(options)ConfigAnchoranchor.path()anchor.exists()/anchor.existsSync()anchor.read()/anchor.readSync()anchor.get(path, defaultValue)/anchor.getSync(path, defaultValue)anchor.has(path)/anchor.hasSync(path)anchor.write(value)/anchor.writeSync(value)anchor.set(path, value)/anchor.setSync(path, value)anchor.delete(path)/anchor.deleteSync(path)anchor.update(updater)/anchor.updateSync(updater)
行为说明
- 配置文件不存在时,
read()/readSync()返回{}。 - 写入时会自动创建父目录。
set()/setSync()会自动创建缺失的中间对象。update()/updateSync()适合将多处修改合并成一次持久化写入。- 写入采用同目录原子替换。
- 文件以 JSON5 形式序列化。
- 写回时会重写整个文件内容,不保留原始注释和排版格式。
