[英]import JSON file with node.js
I want data from the config.json file import to the index.js file in the same dir.我希望将 config.json 文件中的数据导入到同一目录中的 index.js 文件中。
so I had it before所以我以前有过
const {
prefix, token
} = require('./config.json');
now i would change the string so i need a json object, but how?现在我会更改字符串,所以我需要一个 json 对象,但是如何?
In ES5 you can do it by
在 ES5 中,你可以通过
const object = require('./config.json');
The object will contain your JSON.该对象将包含您的 JSON。
In ES6在 ES6 中
import object from './config.json'
Using fs module synchronously
同步使用 fs 模块
const fs = require('fs')
const jsonData = JSON.parse(fs.readFileSync('config.json', 'utf-8'))
If you want the whole object, simply use:如果你想要整个对象,只需使用:
const config = require('./config.json');
Otherwise if you want the contents of config.json
, you can simply use the fs
module to read the file.否则,如果你想要
config.json
的内容,你可以简单地使用fs
模块来读取文件。 More specifically fs.readFileSync
if you want it to be synchronous.更具体地说
fs.readFileSync
如果您希望它是同步的。
Async example, if you're using ES6 modules:异步示例,如果您使用的是 ES6 模块:
import fs from 'fs/promises';
const {prefix, token} = JSON.parse(
await fs.readFile('./config.json', 'utf-8')
);
See also:也可以看看:
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.