node.js - 类型错误:.push() 不是函数
问题描述
我正在使用 discord.js v12,带有 npm 模块 linux-shell-command,在 ubuntu 上运行,并添加了一个功能,可以 ping 我管理的 3 个 Web 域以查看它们是否启动。
var shellCommand = require("linux-shell-command").shellCommand;
var upDown = [];
if (args == []) {
// code not written yet
}
else {
try {
var domain=['example1.com','example2.com','example3.com'];
domain.forEach(site=>{
var sc=shellCommand(`ping -c 1 ${site} |grep '1 received, 0% packet loss'`);
sc.execute(upDown).then(success => {
if (success === true) {
var packet=sc.stdout;
packet=packet.slice(34,-10);
if (packet === " 0% packet loss") {
upDown.push(`The ${site} website is up!`);
}
}
else {
upDown.push(`The ${site} website is down!`);
}
}).catch(e => {
console.error(e);
});
});
}
catch (e) {
console.error(e);
}
finally {
console.log(upDown);
}
}
如果我删除了 forEach,我将不得不为每个域重复其中的代码块,没有 upDown 数组,所以我尝试了这种方式。
upDown.push()
静默失败(不向 upDown 数组添加任何内容),无论存在多少域。
如果我添加upDown=upDown.join("\n");
到finally
块中,在 之前console.log()
,我会为每个域收到此错误,指向.push()
如果域响应会发生的错误。
undefined
TypeError: upDown.push() is not a function
我很困惑,因为如果我在 upDown 数组的声明下使用 push ,我可以毫无问题地推送,如果我在推送之前将 upDown 打印到控制台,它会看到数组,它的内容。(通过手动向数组声明中添加一项来验证)
解决方案
我最终以一种不同的方式实现了这一目标。这是修改后的代码,它完全符合我的要求。
var shellCommand = require("linux-shell-command").shellCommand;
if (args == []) {
//code not written yet
}
else {
try {
var domain=['example1.com','example2.com','example3.com'];
domain.forEach(site =>{
var result;
var sc=shellCommand(`ping -c 1 ${site} |grep '1 received. 0% packet loss'`);
sc.execute().then(success => {
if (success === true) {
result="up";
}
else {
result="down";
}
console.log(`${site} is ${result}!`);
});
});
}
catch (e) {
console.error(e);
}
finally {
console.log("websites were checked!");
}
}
这会将基于结果的执行放在 Promise 中,无需额外的数组,而不会中断流程。
谢谢您的帮助!:)
推荐阅读
- python - 更新dict理解python中的项目
- postgresql - 是否可以更改 postgresql 中索引的执行顺序?
- python - 为什么 Google 会返回“无”坐标
- javascript - cypress 加载从列表中选择的页面
- vue.js - 防止 Vue 多选存储空数组
- javascript - 如何将美人鱼图添加到 Rocket.chat 实例?
- amazon-web-services - 适用于 IaC 的 AWS CDK VS 开发工具包
- java - Java - 使用 .class 文件编译
- reactjs - 如何在匹配减速器中的项目时使用新键和值修改减速器对象的值
- java - 如何使用 Jsoup 获取 html 数据的特定子元素