实现说明
逻辑集中在函数 saveConfig、loadConfig、main里。
异步流被 await 线性化,失败处理保持局部。唯一的导入来源是 node:fs/promises(Node.js 内建),暴露出 readFile、writeFile。
使用要点
- 唯一的导入
node:fs/promises属于 Node.js 标准库。 - 运行整个文件:
main会依次驱动saveConfig、loadConfig。
常见问题
运行之前需要装什么吗?
什么都不用装:node:fs/promises 随 Node.js 本体提供。
主签名形如 async function saveConfig(path: string, config: CacheConfig)
核心语句
await writeFile(path, JSON.stringify(config, null, 2), 'utf8');
await saveConfig(configPath, { maxEntries: 128, ttlMs: 60_000 });
async function loadConfig(path: string): Promise<CacheConfig> {
const raw = await readFile(path, 'utf8');
return JSON.parse(raw) as CacheConfig;
}
代码示例
import { readFile, writeFile } from 'node:fs/promises';
interface CacheConfig {
maxEntries: number;
ttlMs: number;
}
// writeFile serializes the whole config file in one call
async function saveConfig(path: string, config: CacheConfig): Promise<void> {
await writeFile(path, JSON.stringify(config, null, 2), 'utf8');
}
// readFile returns the stored bytes; JSON.parse restores the shape
async function loadConfig(path: string): Promise<CacheConfig> {
const raw = await readFile(path, 'utf8');
return JSON.parse(raw) as CacheConfig;
}
async function main(): Promise<void> {
const configPath = 'cache.config.json';
await saveConfig(configPath, { maxEntries: 128, ttlMs: 60_000 });
const loaded = await loadConfig(configPath);
console.log(`round trip restored: maxEntries=${loaded.maxEntries} ttlMs=${loaded.ttlMs}`);
console.log(`stored bytes: ${(await readFile(configPath, 'utf8')).length}`);
}
main();