这是在 JavaScript SDK 中使用 AWS 全局配置的正确方法吗?
Is this the correct way to use the AWS global config in the JavaScript SDK?
AWS 的配置方式让我觉得很奇怪。您显然可以在一个文件中设置配置,然后您不必 export
配置的 AWS 对象,您可以再次直接从节点模块导入它。我很难理解 how/why 这行得通:
// config.js
const AWS = require('aws-sdk')
AWS.config.update({ region: 'us-east-2', signatureVersion: 'v4' })
然后在其他一些文件中,我可以像这样导入 AWS,并且配置神奇地保持不变:
// some other js file
const AWS = require('aws-sdk') // look, I didn't import this from config.js!
const s3 = new AWS.S3() // it knows how to use the right region & signature!
为什么我不应该导出我配置的 AWS,而是导入它?即使我没有从我的配置文件中导入配置,如何复制配置?
如果您查看 source code,您会发现 AWS
对象具有 config
一个已初始化的 属性。
这基本上是 Node.js 中的 singleton object, it relies on module caching。
来自 NodeJS 文档:
Caching
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.
Provided require.cache is not modified, multiple calls to
require('foo') will not cause the module code to be executed multiple
times. This is an important feature. With it, "partially done" objects
can be returned, thus allowing transitive dependencies to be loaded
even when they would cause cycles.
To have a module execute code multiple times, export a function, and
call that function.
AWS 的配置方式让我觉得很奇怪。您显然可以在一个文件中设置配置,然后您不必 export
配置的 AWS 对象,您可以再次直接从节点模块导入它。我很难理解 how/why 这行得通:
// config.js
const AWS = require('aws-sdk')
AWS.config.update({ region: 'us-east-2', signatureVersion: 'v4' })
然后在其他一些文件中,我可以像这样导入 AWS,并且配置神奇地保持不变:
// some other js file
const AWS = require('aws-sdk') // look, I didn't import this from config.js!
const s3 = new AWS.S3() // it knows how to use the right region & signature!
为什么我不应该导出我配置的 AWS,而是导入它?即使我没有从我的配置文件中导入配置,如何复制配置?
如果您查看 source code,您会发现 AWS
对象具有 config
一个已初始化的 属性。
这基本上是 Node.js 中的 singleton object, it relies on module caching。
来自 NodeJS 文档:
Caching
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.
Provided require.cache is not modified, multiple calls to require('foo') will not cause the module code to be executed multiple times. This is an important feature. With it, "partially done" objects can be returned, thus allowing transitive dependencies to be loaded even when they would cause cycles.
To have a module execute code multiple times, export a function, and call that function.