node.js - 当尝试将变量传递给另一个模块时,将代码拆分到Nodejs中的自定义模块时,它会变得未定义
问题描述
我有一个用于禁用 AWS cloudwatchevents 的 aws lambda。当我不使用自定义模块时,它工作正常,当我尝试使用自定义模块时,我在另一个模块中需要的变量未定义。我做错了什么?var myRuleparams 现在是未定义的我没有把整个代码只是一个片段,所以它很容易理解
这是有效的 index.js
let AWS = require("aws-sdk");
const cloudwatchevents = new AWS.CloudWatchEvents({region: 'us-east-1'});
//var cloudrule = require('./cloudrule');
exports.handler = (event, context, callback) => {
let myRule;
const er = event.resources ;
//miRule is the name of the CloudWatchEventRule that started the lambda
myRule = er[0].slice(43);
var myRuleparams = { Name: myRule };
var rulePromise = cloudwatchevents.disableRule(myRuleparams).promise();
rulePromise.then(
function(data) {
console.log("cloudwatchevent has been disabled");
console.log(data);
}).catch(
function(err) {
console.error(err);
//this works
// more code
这是带有自定义模块 cloudrule.js 的 index.js 不起作用
index.js
let AWS = require("aws-sdk");
const cloudwatchevents = new AWS.CloudWatchEvents({region: 'us-east-1'});
var cloudrule = require('./cloudrule');
exports.handler = (event, context, callback) => {
let myRule;
const er = event.resources;
//miRule is the name of the CloudWatchEventRule that started the lambda
myRule = er[0].slice(43);
var myRuleparams = { Name: myRule };
// here under custom module with functions and passing Variable myRuleparams
cloudrule.disableCloudWatchRuler(myRuleparams);
//more code
这是 cloudrule.js
let AWS = require("aws-sdk");
const cloudwatchevents = new AWS.CloudWatchEvents({region: 'us-east-1'});
module.exports = {
disableCloudWatchRuler: function(myRuleparams) {
var rulePromise = cloudwatchevents.disableRule(myRuleparams).promise();
rulePromise.then(
function(data) {
console.log("cloudwatchevent has been disabled");
console.log(data);
}).catch(
function(err) {
console.error(err);
});
}
};
解决方案
我修复了它需要放 let myRule; 在模块导出之前使其成为全局变量
所以代码应该是这样的
let AWS = require("aws-sdk");
const cloudwatchevents = new AWS.CloudWatchEvents({region: 'us-east-1'});
var cloudrule = require('./cloudrule');
//add let myRule here
let myRule;
exports.handler = (event, context, callback) => {
//remove let myRulefrom here
const er = event.resources;
// more code
推荐阅读
- excel - 如何根据Excel中基于两个日期的条件获取周数
- terraform - 在 Terraform 中多次执行相同的资源
- javascript - 如何通过onclick javascript创建元素后滑动元素
- python - ValueError:不能使用 'rcan/truediv' 作为 'rcan/conv2d/kernel/Initializer/random_uniform/sub' 的输入,因为 'rcan/truediv' 在 while 循环中
- c++ - 我们可以在 C++ 中以枚举数据类型存储字符串吗?
- asp.net - 如何记录asp.net中抛出的异常?
- php - 打印表格pdf功能
- ruby-on-rails - ruby on rails 中的关联 - 用户创建课程
- java - 编译 Java 代码时发生“不兼容类型错误”
- kendo-ui - 如何添加不在 sprite.png 中的剑道编辑器工具图像