Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Does nodejs support "require" for a json file without .json extension

In node 5.0 is there a syntax for require where it will recognize a file as json without the .json extension??

For example I want to be able to read in the .bowerrc file (a json file) with a require statement like this.

var bowerrc = require("./.bowerrc");

but node throws a token error because it thinks it's javascript and not a json file.

if I temporarily change .bowerrc to .bowerrc.json (and the filename as well) then it's all fine so I know this is what is happening.

I see that there is a requirejs plugin for the browser that supports json!nameofile but that doesn't work in node.

like image 798
DKebler Avatar asked Nov 17 '15 06:11

DKebler


People also ask

Does node js support JSON?

The Node runtime environment has the built-in require function and the fs module that you can use for loading or reading JSON files.

How does JSON data work in node JS?

Read JSON From File System In NodeJS: var jsonObj = require("./path/to/myjsonfile. json"); Here, NodeJS automatically read the file, parse the content to a JSON object and assigns that to the left hand side variable. It's as simple as that!


1 Answers

No, there is no way to make require() treat it as JSON if it doesn't have the right file extension.

Instead, you would just have to read the file and parse it yourself.

Here's the relevant portion from the node.js doc:

.js files are interpreted as JavaScript text files, and .json files are parsed as JSON text files. .node files are interpreted as compiled addon modules loaded with dlopen.

LOAD_AS_FILE(X)

  1. If X is a file, load X as JavaScript text. STOP
  2. If X.js is a file, load X.js as JavaScript text. STOP
  3. If X.json is a file, parse X.json to a JavaScript Object. STOP
  4. If X.node is a file, load X.node as binary addon. STOP

You can make your own JSON loader:

function loadJSON(file) {
    var data = fs.readFileSync(file);
    return JSON.parse(data);        
}
like image 181
jfriend00 Avatar answered Nov 02 '22 23:11

jfriend00