jsonnode.jsrequire

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?


Solution

  • As of Node v0.5.x, yes.

    You can require your JSON just as you would require a JS file.

    const someObject = require('./somefile.json')
    

    In ES6:

    import someObject from './somefile.json'