I've encountered a completely incomprehensible behavior of calling a function inside a function. When I call telegram() function inside runParser() after fs.writeFile it just doesn't work. But if I execute it outside runParser() function, it works properly. That said, I have a log() function that gives me a console.log with text. It works. Why is this happening, can I call it inside the function? Also, I noticed that if I put the function at the beginning of try block it works.
const puppeteer = require('puppeteer');
const fs = require('fs');
const url = 'https://rezka.ag/films/page/';
const watched = '/?filter=watching';
const telegram = require('./telegram.js')
const {Bot} = require("tgapi");
const log=require('./log')
////дата
let today = new Date();
let dd = String(today.getDate()).padStart(2, '0');
let mm = String(today.getMonth() + 1).padStart(2, '0')
let yyyy = today.getFullYear();
today = mm + dd + yyyy;
////
let runParser = async () => {
let flag = true
let itog = []
let counter = 1
let browser = await puppeteer.launch({
headless: true,
slowMo: 100,
devtools: true
})
try {
let page = await browser.newPage()
await page.setViewport({width: 1400, height: 900})
while (flag) {
await page.goto(`${url}${counter}${watched}`)
await page.waitForSelector('div.b-footer__right')
let html = await page.evaluate(async () => {
let page = []
try {
let divs = document.querySelectorAll('div.b-content__inline_item')
divs.forEach(div => {
let a = div.querySelector('#main > div.b-container.b-content.b-wrapper > div.b-content__inline > div > div.b-content__inline_items > div > div.b-content__inline_item-link > a')
let obj = {
link: a.href,
title: a.innerText,
info: div.querySelector('#main > div.b-container.b-content.b-wrapper > div.b-content__inline > div > div.b-content__inline_items > div> div.b-content__inline_item-link > div').innerText
}
page.push(obj)
})
} catch (e) {
console.log(e)
}
return page
}, {waitUntil: 'div.b-footer__right'})
itog.push(html)
console.log(itog)
for (let i = 0; i < counter; i++) {
if (counter === 5) {
flag = false
}
}
counter++
}
await browser.close()
fs.writeFile(`movie ${today}.json`, JSON.stringify({data: itog}), err => {
if (err) throw err
console.log('saved')
})
telegram(today)
log()
} catch (e) {
console.log(e)
await browser.close()
}
return JSON.stringify(itog)
}
module.exports = runParser
telegram.js
const {Bot} = require("tgapi");
const fs = require("fs");
const telegram = function (today) {
const bot = new Bot('TOKEN')
const chat_id = 123456
const document = fs.createReadStream(`movie ${today}.json`)
bot
.sendDocument({chat_id, document})
.then(console.log)
}
module.exports = telegram
log.js
function log(){
console.log("work well")
}
module.exports=log