2021年3月14日星期日

TypeError: .push() is not a function

I'm using discord.js v12, with the npm module linux-shell-command, run on ubuntu, and have added a feature that pings 3 web domains I manage to see if they're up.

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);      }  }  

if I removed the forEach, I would have to essentially repeat the code block inside it for each domain, without the upDown array, so I tried it this way.

upDown.push() silently fails (nothing is added to the upDown array), no matter how many domains are present.

if I add upDown=upDown.join("\n"); to the finally block, before the console.log(), I get this error for each domain, pointing to the .push() that happens if the domain responds.

undefined  TypeError: upDown.push() is not a function  

I'm totally confused, because if I use push right under the declaration of the upDown array, I can push no problem, and if I print upDown to the console just before that push, it sees the array, and it's contents. (verified by manually adding an item to the array declaration)

https://stackoverflow.com/questions/66631498/typeerror-push-is-not-a-function March 15, 2021 at 10:05AM

没有评论:

发表评论