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.
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.
Is there something similar for require that enables me to load a JSON file?
The simplest way to read a JSON file is to require it. Passing require() with the path to a JSON file will synchronously read and parse the data into a JavaScript object. const config = require("./config. json");
The package. json file is the heart of any Node project. It records important metadata about a project which is required before publishing to NPM, and also defines functional attributes of a project that npm uses to install dependencies, run scripts, and identify the entry point to our package.
node. js is built on Google Chrome's V8 engine, which adheres to ECMA standard. Therefore, node. js also has a global object JSON [docs].
Answers related to “package. json is required by node runtime” To load an ES module, set "type": "module" in the package.
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')
In ES6:
import someObject from ('./somefile.json')
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With