У меня есть код, который удаляет определенную страницу. Для этого я использую кукольник + чирио. На моем ноутбуке код работает отлично. Но после его развертывания на VDS селектор cheerio each () начал странно работать. (Но на моем ноутбуке все еще отлично работает). Проблема в том, что на VDS возникает следующая ошибка:
(node:28544) UnhandledPromiseRejectionWarning: TypeError: Cannot read property 'trim' of undefined at Node. (/home/ubuntu/handbot/liveMonitoring.js:211:82) at initialize.exports.each (/home/ubuntu/handbot/node_modules/cheerio/lib/api/traversing.js:300:24) at Node. (/home/ubuntu/handbot/liveMonitoring.js:182:29) at initialize.exports.each (/home/ubuntu/handbot/node_modules/cheerio/lib/api/traversing.js:300:24) at liveMonitoring (/home/ubuntu/handbot/liveMonitoring.js:175:28) at process._tickCallback (internal/process/next_tick.js:68:7) (node:28544) UnhandledPromiseRejectionWarning: Unhandled promise rejection. This error originated either by throwing inside of an async function without a catch block, or by rejecting a promise which was not handled with .catch(). (rejection id: 1) (node:28544) [DEP0018] DeprecationWarning: Unhandled promise rejections are deprecated. In the future, promise rejections that are not handled will terminate the Node.js process with a non-zero exit code.
Самым интересным моментом является то, что иногда ошибка исчезает (похоже, нет шаблона, в котором возникает ошибка). Я пытался решить эту проблему, переустановив node js, но это не сработало. Проблема не в моем коде (так как он работает на моем ноутбуке и даже иногда на vds). Я думаю, что есть что-то с экспортом функции each (). Поскольку из-за сообщения об ошибке в
/home/ubuntu/handbot/node_modules/cheerio/lib/api/traversing.js:300:24
Код traversing.js (298-302 строки):
`
exports.each = function(fn) {
var i = 0, len = this.length;
while (i < len && fn.call(this[i], i,
this[i]) !== false) ++i;
return this;
};
Код, вызывающий ошибку:
const page = await browser.newPage();
await page.goto(url, {timeout:0}).catch((err)=> { console.info(err)});
await page.setRequestInterception(true);
page.on('request', req => {
if (['image', 'stylesheet', 'font'].indexOf(req.resourceType()) !== -1)
req.abort();
else
req.continue();
});
let content = await page.content();
let $ = cheerio.load(content);
let gameContent=$('#games_content').children('div').children('div');
gameContent.children().each(function(i, elem1){
let league=$(elem1).children('.greenBack').children('.c-events__name').children('a').text().trim();
$(this).children().each(function(j, elem2){
if (j!==0) {
let currentInfo = {};
currentInfo['league'] = league;
let shortCut = $(elem2).children('.c-events__item_game').children('.c-events-scoreboard').children();
let mainInfo = shortCut.first();
currentInfo['link'] = mainInfo.children("a").attr("href");
let teams = mainInfo.children("a").children("span").attr("title").trim().split("—");
currentInfo['team1'] = teams[0].trim();
currentInfo['team2'] = teams[1].trim();
let shortCutForTotal = $(elem2).children('.c-events__item_game').children('.c-bets');
}
});
});
Заранее спасибо! `
Да. Но я не обнаружил, что в этой части моего кода что-то не так. Больше всего сбивает с толку то, что иногда мой код работает, иногда возникает ошибка. Так что я действительно не знаю, что делать дальше
Я обновил пост. Благодарю за совет



![Безумие обратных вызовов в javascript [JS]](https://i.imgur.com/WsjO6zJb.png)


Проблема была решена путем изменения этих строк кода:
page.on('request', req => {
if (['image', 'stylesheet', 'font'].indexOf(req.resourceType()) !== -1)
req.abort();
else
req.continue();
})
со следующими:
page.on('request', interceptedRequest => {
if (interceptedRequest.url().endsWith('.png') || interceptedRequest.url().endsWith('.jpg') || interceptedRequest.url().endsWith('.css'))
interceptedRequest.abort();
else
interceptedRequest.continue();
});
и размещение await page.goto(url); после вышеприведенных строк кода.
Затем добавляем опцию waitUntil:'networkidle0' в page.goto(url)
Вы читали эту часть сообщения об ошибке:
Cannot read property 'trim' of undefined at Node. (/home/ubuntu/handbot/liveMonitoring.js:211:82)Я не думаю, что эта проблема имеет какое-либо отношение кeach, это просто часть трассировки стека