Node.js (connect ECONNREFUSED 127.0.0.1:43645)

Всем привет! Это мой первый вопрос и если я что-то сделал не так, прошу простить) У меня есть клиент-серверное приложение на node.js и оно работает. Работает правильно. Но бывают моменты, что оно отработало какое-то время и выдает следующую ошибку:

node version - 10.15.2

{ Error: connect ECONNREFUSED 127.0.0.1:43645
    at TCPConnectWrap.afterConnect [as oncomplete] (net.js:1104:14)
  errno: 'ECONNREFUSED',
  code: 'ECONNREFUSED',
  syscall: 'connect',
  address: '127.0.0.1',
  port: 43645 }

Время прекращения работоспособности и выдачи ошибки - всегда разное и как я заметил по логам, она может происходить в любом участке кода (видно в каком месте оборвались логи)

Участок кода, в котором выскакивает ошибка. Вот например последний раз все остановилось на logIntoFile(user.email, "Парсинг по товару " + ourItem.name, config.messageStatus.success); так как других логов нет. Только ошибка.

     //console.log("Парсинг по товару", ourItem.name);
      logIntoFile(user.email, "Парсинг по товару " + ourItem.name, config.messageStatus.success);

      var [error, res, body] = await ozonRequest('/v2/product/info', user.ozonClientId, user.ozonApiKey,
          {
            "offer_id": ourItem.art
          });

        // console.log("ERROR:")
        // console.log(error)

        // console.log("RES:")
        // console.log(res)

        // console.log("BODY:")
        // console.log(body)

      if (error) 
      {
        console.error("Артикул", ourItem.art, error.message);
        return true;
      }

      let ourCurrentPrice = Number(body.result.price); // Наша текущая цена по товару

      let minPriceItem = { seller: null, price: null }; // Определение селлера с минимальной ценой

      var linksData = []; // Ссылки на конкурентов
      var links = ourItem.links.split('\n');

      await asyncForEach(links, async link => // Проходимся по ссылкам
      {
        let linkData = await this.getLinkData(link);
        linksData.push(linkData);
      });

        await asyncForEach(linksData, async linkData => 
        {
            if (linkData.price && linkData.seller) 
            {
                if (linkData.seller.toLowerCase() != user.sellerName.toLowerCase()) // Если это ссылка не на нашу страницу с товаром
                {
                    // Если текущая определенная минимальная цена и новая спарсенная > текущая определенная минимальная цена
                    if (minPriceItem.price && linkData.price > minPriceItem.price) 
                    {
                        //console.log("[" + user.email + "][" + linkData.seller + "] " + linkData.price + " > " + minPriceItem.price);
                        logIntoFile(user.email, "[" + linkData.seller + "] " + linkData.price + " > " + minPriceItem.price);
                    } 
                    else if (linkData.abroad && !ourItem.abroad) 
                    {
                        //console.log("[" + user.email + "][" + linkData.seller + "] цена игнорируется (доставка из-за рубежа)");
                        logIntoFile(user.email, "[" + linkData.seller + "] цена игнорируется (доставка из-за рубежа)");
                    } 
                    else 
                    {
                        if (minPriceItem.seller == null || minPriceItem.price == null) 
                        {
                            //console.log("[" + user.email + "][" + linkData.seller + "] Найдена цена " + linkData.price);
                            logIntoFile(user.email, "[" + linkData.seller + "] Найдена цена " + linkData.price);
                        } 
                        else 
                        {
                            console.log("[" + user.email + "][" + linkData.seller + "] " + linkData.price + " <= " + minPriceItem.price);
                            logIntoFile(user.email, "[" + linkData.seller + "] " + linkData.price + " <= " + minPriceItem.price);
                        }

                        minPriceItem.price = linkData.price;
                        //console.log(linkData.price);
                        minPriceItem.seller = linkData.seller;
                    }
                } 
                else 
                {
                    //console.log("[" + user.email + "][" + user.sellerName + "] " + linkData.price + " (наша цена)");
                    logIntoFile(user.email, "[" + user.sellerName + "] " + linkData.price + " (наша цена)");
                }
            }
            else 
            {
                console.log("[" + user.email + "] Seller:", linkData.seller, "; price:", linkData.price, ". Check product at " + linkData.link);
                logIntoFile(this.username, "Не найден товар по адресу " + linkData.link, config.messageStatus.warning);
            }
        });

      let actualPrice = minPriceItem.price;
      let ourMinPrice = ourItem.minPrice;

      //itemInBuyBox - Товар находится на BuyBox

      //minPriceItem.seller - селлер с минимальной ценой
      //minPriceItem.price - цена товара селлера с минимальной ценой
      //actualPrice - актуальная цена на товар
      //ourItem - наш товар
      //ourMinPrice - наша минимальная цена на товар

      let itemInBuyBox = false;
      if (minPriceItem.seller) {
        console.log("Товар '" + ourItem.name + "'. Минимальная цена :", actualPrice, "(", minPriceItem.seller, "),  наша минимально-допустимая", ourMinPrice);
        logIntoFile(user.email, "[" + minPriceItem.seller + "] Минимальная найденная цена - " + actualPrice);

        console.log(actualPrice);
        let newPrice =  parseInt(actualPrice.replace(/[^0-9]/,''))-1;
        var hi = 1;

        console.log("new price - " + newPrice + " | actualPrice - " + actualPrice + " | hi - " + hi);
        itemInBuyBox = Boolean(newPrice >= ourMinPrice);


        if (!itemInBuyBox) {
          //console.log("Не меняем цену товара " + ourItem.name + " на " + (newPrice) + " т.к. она ниже допустимого");
          logIntoFile(user.email, "Не меняем цену товара " + ourItem.name + " на " + newPrice + " т.к. она ниже допустимого");
        }

        else if (ourCurrentPrice != newPrice) {
          priceChangeCount++;
          //console.log("Меняем цену товара " + ourItem.name + " на " + newPrice);
          logIntoFile(user.email, "Меняем цену товара " + ourItem.name + " на " + newPrice, config.messageStatus.success);
          this.setPrice(ourItem.art, (newPrice), user);
        } else {
          logIntoFile(user.email, "Текущая цена " + ourCurrentPrice + " не меняется");
        }
      } else {
        //console.log("По товару " + ourItem.name + " не найдено чужих цен");
        logIntoFile(user.email, "По товару " + ourItem.name + " не найдено чужих цен");
        if (ourItem.maxPrice && Number(ourItem.maxPrice) != ourCurrentPrice) {
          console.log(ourItem.maxPrice + '<>' + ourCurrentPrice);
          itemInBuyBox = true;
          priceChangeCount++;
          logIntoFile(user.email, "Устанавливаем свою максимальную цену на " + ourItem.name, config.messageStatus.success);
          this.setPrice(ourItem.art, ourItem.maxPrice, user);
        }
        else this.setPrice(ourItem.art, ourCurrentPrice, user, false);
      }
      this.setBuyBox(ourItem.art, user, itemInBuyBox);
    });

    this.addPriceChangeCount(priceChangeCount);
    await this.nextLoop();
  };

  async nextLoop() {
    this.dispose();
    //console.log('Авторепрайсинг завершён. Следующий запуск через ' + config.minutes + ' минут');
    logIntoFile(this.username, 'Авторепрайсинг завершён. Следующий запуск через ' + config.minutes + ' минут', config.messageStatus.success);
    this.timer = setTimeout(() => { this.init() }, config.minutes * 60 * 1000);
  };

  async addPriceChangeCount(count){
    this.db.collection('counters').updateOne({name: 'priceChange'},
        {
          $inc: {
            value: count
          }
        });
  };

Буду рад и благодарен любому совету) Всем добра!


Ответы (0 шт):