node.js 中是否需要 json [英] is there a require for json in node.js

查看:31
本文介绍了node.js 中是否需要 json的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想在我的 JavaScript 代码中包含几个 JSON 文件,这些文件与我的 JavaScript 源文件位于同一目录中.

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.

是否有类似的 require 使我能够加载 JSON 文件?

Is there something similar for require that enables me to load a JSON file?

推荐答案

从 node 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的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆