Exploring Node.js Modules: Using JSON modules

Node.js supports using require(‘./path/to/file-name.json’) to import a JSON file in a CommonJS module. It is equivalent to the following 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 data = require(‘./data.json’);

console.log(data);

It will execute as follows:

$ node showdata.js

{ hello: ‘Hello, world!’, meaning: 42 } 

The console.log function outputs information to the Terminal. When it receives an object, it prints out the object content like this. And this demonstrates that require correctly read the JSON file since the resulting object matched the JSON.

In an ES6 module, this is done with the import statement and requires a special flag. Create a file named showdata-es6.mjs containing the following:

import * as data from ‘./data.json’;

console.log(data);

So far that is equivalent to the CommonJS version of this script, but using import rather than require.

$ node –experimental-modules –experimental-json-modules showdata- es6.mjs

(node:12772) ExperimentalWarning: The ESM module loader is experimental.

[Module] { default: { hello: ‘Hello, world!’, meaning: 42 } } 

Currently using import to load a JSON file is an experimental feature. Enabling the feature requires these command-line arguments, causing this warning to be printed. We also see that instead of data being an anonymous object, it is an object with the type Module.

Now let’s look at how to use ES6 modules on some older Node.js releases.

Source: Herron David (2020), Node.js Web Development: Server-side web development made easy with Node 14 using practical examples, Packt Publishing.

Leave a Reply

Your email address will not be published. Required fields are marked *