NodeJS TypeError:无法读取未定义的属性'substr'

ttp71kqs  于 2022-12-12  发布在  Node.js
关注(0)|答案(1)|浏览(126)

我突然开始得到这个错误不知从哪里来的几个星期没有问题,我似乎不能找出是什么原因造成的。

TypeError: Cannot read property 'substr' of undefined
    at getFullNumber (C:\Bots\Cafe\Cafe Team Bot ver 2.4.0\commands\opt.js:13:31)
    at init (C:\Bots\Cafe\Cafe Team Bot ver 2.4.0\commands\opt.js:149:20)
    at Request._callback (C:\Bots\Cafe\Cafe Team Bot ver 2.4.0\commands\opt.js:139:25)
    at Request.self.callback (C:\Bots\Cafe\Cafe Team Bot ver 2.4.0\node_modules\request\request.js:185:22)
    at Request.emit (events.js:189:13)
    at Request.<anonymous> (C:\Bots\Cafe\Cafe Team Bot ver 2.4.0\node_modules\request\request.js:1161:10)
    at Request.emit (events.js:189:13)
    at IncomingMessage.<anonymous> (C:\Bots\Cafe\Cafe Team Bot ver 2.4.0\node_modules\request\request.js:1083:12)
    at Object.onceWrapper (events.js:277:13)
    at IncomingMessage.emit (events.js:194:15)

它似乎指向了函数。

function getFullNumber(cash){
        var newcash = -1;
        if(!isNaN(Number(cash))){
            newcash = Number(cash);
        } else {
            var suffix = cash.substr(cash.length-1);
            suffix = suffix.toLocaleUpperCase();
            switch(suffix){
                case "K":
                    newcash = Number(cash.substr(0,cash.length-1))*1000;
                    break;
                case "M":
                    newcash = Number(cash.substr(0,cash.length-1))*1000000;
                    break;
                case "B":
                    newcash = Number(cash.substr(0,cash.length-1))*1000000000;
                    break;
                case "T":
                    newcash = Number(cash.substr(0,cash.length-1))*1000000000000;
                    break;
                case "Q":
                    newcash = Number(cash.substr(0,cash.length-1))*1000000000000000;
                    break;
            }
        }
        return newcash;
    }

function init(cash){
    try {
        cash = getFullNumber(cash);
        if(cash <= 0) return;
        var userData = JSON.parse(fs.readFileSync(client.config.dataFolder + "/users/" + currentUser + ".json", "utf8"));
        var arr = getMaxItems(userData, cash);
        if(arr){
            if(arr.length==0){
                client.users.get(currentUser).send("You Need More Cash!");
            } else {
                var text = ahk(arr);
                var file = client.config.dataFolder + "/ahks/" + getFileName();
                fs.writeFileSync(file, text);
                client.users.get(currentUser).send({
                      files: [{
                          //attachment: 'C:/Bots/Cafe/Cafe Team Bot ver 2.4.0/test.ahk',
                        attachment: file,
                        name: 'Ahk-' + displayTime() +'.ahk'
                      }]
                    });
            }
        }
        //if(str.length>0)
            //client.users.get(currentUser).send(str + "\n`++++++++++++++++++++++++++++++`");
    } catch(err){
        console.log(err);
    }
}

不知道为什么这开始发生的蓝色,但任何帮助将是梦幻般的!

const fs = require("fs");
const request = require("request");
exports.run = (client, message, args) => {
    var currentUser = message.author.id;
    var file = client.config.dataFolder + "/users/" + currentUser + ".json";
    if(!fs.existsSync(file)) return;
    //convert numbers with K,M,B,T to real numbers
    function getFullNumber(cash){
        var newcash = -1;
        if(!isNaN(Number(cash))){
            newcash = Number(cash);
        } else {
            var suffix = cash.substr(cash.length-1);
            suffix = suffix.toLocaleUpperCase();
            switch(suffix){
                case "K":
                    newcash = Number(cash.substr(0,cash.length-1))*1000;
                    break;
                case "M":
                    newcash = Number(cash.substr(0,cash.length-1))*1000000;
                    break;
                case "B":
                    newcash = Number(cash.substr(0,cash.length-1))*1000000000;
                    break;
                case "T":
                    newcash = Number(cash.substr(0,cash.length-1))*1000000000000;
                    break;
                case "Q":
                    newcash = Number(cash.substr(0,cash.length-1))*1000000000000000;
                    break;
                    
            }
                        
        }
        return newcash;
    }
    function addSuffix(num){
        if(num<1000)return parseFloat(num.toFixed(2)).toString();
        else if(num<1000000) return parseFloat((num/1000).toFixed(2)).toString() + "K";
        else if(num<1000000000) return parseFloat((num/1000000).toFixed(2)).toString() + "M";
        else if(num<1000000000000) return parseFloat((num/1000000000).toFixed(2)).toString() + "B";
        else if(num<1000000000000000) return parseFloat((num/1000000000000).toFixed(2)).toString() + "T";
        else return parseFloat((num/1000000000000000).toFixed(2)).toString() + "Q";
    }
    function decaf(items){
        var decafItems = ["Brewer","Grinder","Shelving","Wifi","Ice-Machine","Blender","Table","Dishwasher"];
        var decafObj = {};
        for(var item in items){
            if (decafItems.includes(item))
                decafObj[item] = items[item];
        }
        return decafObj;
    }
    //return a string list of items with count
    //as per the cash you have
    function getMaxItems(userData, cash, first){
        var allItems = ["Brewer","Grinder","Shelving","Wifi","Ice-Machine","Blender","Table","Dishwasher","Seat","Espresso","Boiler","Wastebin","Refrigerator","Infuser","Sofa","Dispenser","Creamer","Press","Pitcher","Urn","Airpot","Sleeve-Holder","Warmers","Spigot","Juicer","Teapot","Pump","Delivery","Grill","Knock-Box","Spice-Rack","Hoppers","Toaster","Oven","Microwave","Farm","Transport","Solar","Radio"];
        var uData = userData.list == 'decaf' ? decaf(userData.items) : userData.items;
        
        var best = getCalculatedBest(uData, cash);
        if(best == "")
            return [];
        uData[best].count++;
        var obj = {};
        obj[best] = {count:1};
        var amount = 0;
        while(amount < cash){
            amount += (uData[best].count-1)*client.config.items[best].increment + client.config.items[best].basePrice;
            best = getCalculatedBest(uData, cash - amount);
            //if there are no items left to buy with the left cash amount
            if(best == "") break;
            
            uData[best].count++;
            if(!obj[best])obj[best] = {count:0};
            obj[best].count++;
        }
        var arrItems = [];
        for(var item in obj){
            arrItems.push({name :item, data: obj[item]});
        }
        arrItems.sort(function(a,b){
            return allItems.indexOf(a.name) - allItems.indexOf(b.name);
        });
        var strArr = [];
        for(var i in arrItems)
            strArr.push(".b " + arrItems[i].name + " " + arrItems[i].data.count);
        return strArr;
    }
    //get the best item to buy by increments calculation
    function getCalculatedBest(uData, cash){
        var min = {
            name: '',
            cpsPer: Number.MAX_SAFE_INTEGER
        };
        var firstZero = true;
        for(var name in uData){
            if(uData[name].count==0){
                if(firstZero)
                    firstZero = false;
                else 
                    continue;
            }
            uData[name].price = uData[name].count *client.config.items[name].increment + client.config.items[name].basePrice;
            //check only the items that have prices lower than the opt cash
            if(uData[name].price<=cash)
                if(uData[name].price/uData[name].cps < min.cpsPer){
                    min.cpsPer = uData[name].price/uData[name].cps;
                    min.name = name;
                }
        }
        return min.name;
    }
    //get the cash using the api
    function getUserInfo(){
        try{
            request(
                {
                    url : "https://the-kirb.club/api/u/" + currentUser,
                    headers : {
                        "Authorization" : client.config.apikey
                    }
                },
                function (error, response, body) {
                    if(body){
                        var data = JSON.parse(body);
                        init(data.cash);
                    }
                }
            );
        }catch(err){
            console.log(err);
        }
    }
    function getFileName(){
        var dd = new Date();
        return dd.getFullYear().toString()+dd.getMonth().toString()+dd.getUTCDate().toString()+
            dd.getMinutes().toString()+dd.getSeconds().toString() + dd.getMilliseconds().toString() +
            (Math.random()*100).toFixed(0) + ".ahk";
    }

   
    function ahk(arr){
        var str = '#SingleInstance,force\n';
        str += 'Your_List:= ' + JSON.stringify(arr) + "\n";
        str += '*f3::\n';
        str += '    For,k,v in Your_List\n';
        str += '        {\n';
        str += '            SendInput,% Your_List[k]\n';
        str += '            SendInput {Enter}\n';
        str += '            Sleep,5500\n';
        str += '        }\n';
        str += 'esc::Exitapp\n';
        str += '    return';

        return str;
    }

        function displayTime() {
    var str = "";

    var currentTime = new Date()
    var hours = currentTime.getHours()
    var minutes = currentTime.getMinutes()
    var seconds = currentTime.getSeconds()

    if (minutes < 10) {
        minutes = "0" + minutes
    }
    if (seconds < 10) {
        seconds = "0" + seconds
    }
    str += hours + ":" + minutes + ":" + seconds + " ";
    if(hours > 11){
        str += "PM"
    } else {
        str += "AM"
    }
    return str;
}

    function init(cash){
        try {
            cash = getFullNumber(cash);
            if(cash <= 0) return;
            var userData = JSON.parse(fs.readFileSync(client.config.dataFolder + "/users/" + currentUser + ".json", "utf8"));
            var arr = getMaxItems(userData, cash);
            if(arr){
                if(arr.length==0){
                    client.users.get(currentUser).send("You Need More Cash!");
                } else {
                    var text = ahk(arr);
                    var file = client.config.dataFolder + "/ahks/" + getFileName();
                    fs.writeFileSync(file, text);
                    client.users.get(currentUser).send({
                          files: [{
                              //attachment: 'C:/Bots/Cafe/Cafe Team Bot ver 2.4.0/test.ahk',
                            attachment: file,
                            name: 'Ahk-' + displayTime() +'.ahk'
                          }]
                        });
                }
            }
            //if(str.length>0)
                //client.users.get(currentUser).send(str + "\n`++++++++++++++++++++++++++++++`");
        } catch(err){
            console.log(err);
        }
    }
    
    if(args.length==0)
        getUserInfo();
    else {
        var cash = args[0];
        init(cash);
    }
}

编辑以具有整个文件。

qzwqbdag

qzwqbdag1#

看起来,init函数向getFullNumber传递了不正确的参数。只需设置一些保护来检查cash是否为字符串类型。可能类似于

else if(typeof cash === 'string') { 
  var suffix = cash.substr(cash.length-1);
  ... 
}
// Let the newcash default value return.

编辑以包括最大的示例。

function getFullNumber(cash){
        var newcash = -1;
        if(!isNaN(Number(cash))){
            newcash = Number(cash);
        } 
        else if(typeof cash === 'string') { 
            var suffix = cash.substr(cash.length-1);
            suffix = suffix.toLocaleUpperCase();
            switch(suffix){
                case "K":
                    newcash = Number(cash.substr(0,cash.length-1))*1000;
                    break;
                case "M":
                    newcash = Number(cash.substr(0,cash.length-1))*1000000;
                    break;
                case "B":
                    newcash = Number(cash.substr(0,cash.length-1))*1000000000;
                    break;
                case "T":
                    newcash = Number(cash.substr(0,cash.length-1))*1000000000000;
                    break;
                case "Q":
                    newcash = Number(cash.substr(0,cash.length-1))*1000000000000000;
                    break;
            }
        }
        return newcash;
    }

相关问题