JSON modules

Node.js supports using require('/path/to/file-name.json') to import a JSON file. It is equivalent to this code:

const fs = require('fs');module.exports = JSON.parse(        fs.readFileSync('/path/to/file-name.json', 'utf8'));

That is, the JSON file is read synchronously, and the text is parsed as JSON. The resultant object is available as the object exported from the module. Create a file named data.json, containing the following:

{     "hello": "Hello, world!",     "meaning": 42 }

Now create a file named showdata.js, containing the following:

const util = require('util');const data = require('./data');console.log(util.inspect(data));

It will execute as follows:

$ node showdata.js { hello: 'Hello, world!', meaning: 42 }

The util.inspect

Get Node.js Web Development - Fourth Edition now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.