Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

is there a require for json in node.js

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?

like image 503
Corno Avatar asked Aug 23 '11 14:08

Corno


People also ask

How do I require a JSON file in node JS?

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");

Does node js need package 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.

Is JSON part of node JS?

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].

Is package JSON required by the node runtime?

Answers related to “package. json is required by node runtime” To load an ES module, set "type": "module" in the package.


1 Answers

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')

like image 136
goatslacker Avatar answered Oct 20 '22 17:10

goatslacker