Andrei Oniga
Andrei Oniga

Reputation: 8559

In Node.js, does a required module load multiple times if requested multiple times?

An application I'm building is reliant on several .json configuration files. Because I need the same configuration data to be persistent across the application's modules, I've created an individual config.js module where I parse the .json files and export a singular object:

var fs = require("fs");
module.exports = {
    a: JSON.parse(fs.readFileSync("./config/a.json")),
    b: JSON.parse(fs.readFileSync("./config/b.json")),
    c: JSON.parse(fs.readFileSync("./config/c.json"))
};

Considering that I require the config.js module in multiple other modules, will the parsing of the json files run each time the config module is required? Or is Node smart enough to run the JSON.parse() function only the first time and subsequently use the cached results?

Upvotes: 1

Views: 1741

Answers (1)

ZachRabbit
ZachRabbit

Reputation: 5174

Node will cache modules the first time they are loaded, so the code will only run once.

http://nodejs.org/api/modules.html#modules_caching

There's some other interesting information in there, such as for the purpose of config, you can require() JSON files. It's a bit easier than using fs.

Upvotes: 4

Related Questions