首页 > 解决方案 > 类型错误:.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 打印到控制台,它会看到数组,它的内容。(通过手动向数组声明中添加一项来验证)

标签: node.jsdiscord.js

解决方案


我最终以一种不同的方式实现了这一目标。这是修改后的代码,它完全符合我的要求。

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 中,无需额外的数组,而不会中断流程。

谢谢您的帮助!:)


推荐阅读