问题描述
我想在我的JavaScript代码中包含与我的JavaScript源文件在同一目录中的几个JSON文件.
I would like to include a couple of JSON files in my JavaScript code that are in the same directory as my JavaScript source file.
如果我想包含另一个JavaScript文件,我可以简单地使用require
.现在,我使用readFileSync
和__dirname
来获取JSON,我认为这是一种难看的方法.
If I wanted to include another JavaScript file I could simply use require
.Now I'm using readFileSync
and __dirname
to get the JSON, which I think is an ugly way to do it.
是否有类似的要求,使我能够加载JSON文件?
Is there something similar for require that enables me to load a JSON file?
推荐答案
从节点v0.5.x开始,是的,您可以像需要js文件一样要求JSON.
As of node v0.5.x yes you can require your JSON just as you would require a js file.
var someObject = require('./somefile.json')
在ES6中:
import someObject from ('./somefile.json')
这篇关于在node.js中是否需要json的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!