← 中文资源

简体中文版本

fs.promises 写读配置文件往返

用 fs.promises 的 writeFile 写入 JSON 配置文件,再用 readFile 读回并 JSON.parse 解析:一次 async 流程完成配置的落盘与回读,类型随接口保持收窄。

阅读英文原文

运行结果

以下输出由构建管线在沙箱中真实运行该示例捕获。

round trip restored: maxEntries=128 ttlMs=60000
stored bytes: 41

实现说明

逻辑集中在函数 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();