有些本地小工具只需要读一个配置文件,不一定要先引入额外库。Node 自带的 fs/promises 配 JSON.parse 就能处理最简单的场景。
环境:Node.js 18+。可以新建两个文件:
// config.json
{
"name": "demo",
"port": 3000
}
// read-config.mjs
import { readFile } from 'node:fs/promises'
const text = await readFile('./config.json', 'utf8')
const config = JSON.parse(text)
console.log(config.name)
console.log(config.port + 1)
然后跑:
node read-config.mjs
会看到:
demo
3001
这个只适合可信的本地配置。要是配置来自用户上传或者远端接口,还是要再做字段校验,不然读出来的结构不一定是代码想要的样子。