我有一些需要数据库访问的文件,所以我有一个像这样的文件:
...
var dynamo = new AWS.DynamoDB.DocumentClient();
module.exports.getDatabase= function(){
return dynamo;
};
...
我想知道不同的 .js 文件是否像这样使用它:
var DataUtil = require('./shared/dataUtils.js');
...
var database = DataUtil.getDatabase();
....
他们使用的是同一个对象实例吗?或者只是使用要求实例化每个 .js 文件的副本?
最佳答案
是的,这是同一个实例。当您需要一个模块时,它仅在尚未加载时才加载。因此, Node 程序中的模块只有一个实例。
Modules are cached after the first time they are loaded. This means (among other things) that every call to require('foo') will get exactly the same object returned, if it would resolve to the same file.
就您而言,您只有一个 AWS.DynamoDB.DocumentClient
实例。
关于javascript - 关于node.js/javascript在文件之间共享变量,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36909296/