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.
The Node runtime environment has the built-in require function and the fs module that you can use for loading or reading JSON files.
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!
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)
- If X is a file, load X as JavaScript text. STOP
- If X.js is a file, load X.js as JavaScript text. STOP
- If X.json is a file, parse X.json to a JavaScript Object. STOP
- 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);
}
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