在Node.js中,多次请求多次加载所需的模块?

我正在构build的应用程序依赖于几个.jsonconfiguration文件。 因为我需要相同的configuration数据在整个应用程序的模块中保持不变,所以我创build了一个单独的config.js模块,用于parsing.json文件并导出单个对象:

 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")) }; 

考虑到我require多个其他模块中的config.js模块,每次需要configuration模块时,json文件的parsing是否会运行? 还是节点足够聪明,只能在第一次运行JSON.parse()函数,然后使用caching结果?

节点会在第一次加载时caching模块,所以代码只运行一次。

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

还有其他一些有趣的信息,比如为了configuration的目的,你可以require() JSON文件。 这比使用fs更容易一些。