I'm creating a cli for the first time and I've never really coded with Node before but I'm used to JS for front-end website dev. As part of the cli I'm making I'm using Clack.cc for the prompts as I liked the design and the purpose of the cli is to run youtube-dl. Just for fun.
After a few questions, my cli checks to see if a cookie file for a website with the current date is present and if not wait for it to be added by the user. Once added it will automatically rename the file and then continue with the script. However, it renames the file as it should and stops the Clack.cc spinner but instead of continuing the oclif quits.
My function is like so:
if (!hasCookies) {
// If no cookie file found then wait for it to be added
p.log.step(`${color.bgRed(color.black(` An up to date cookie file does not exist in the ${String(dirName)} directory `))}`)
let cookieCheckCount = 1
let nowHasCookie = false
// Wait for cookie file to be added
sp.start('Waiting for cookie file')
const checkFile = async () => {
if (fs.existsSync(cookieFileNoDate) || fs.existsSync(formattedCookieFile)) {
if (fs.existsSync(cookieFileNoDate)) {
await fs.rename(cookieFileNoDate, formattedCookieFile, (err) => {
if (err) {
if (process.env.NODE_ENV === 'development') console.error(err)
} else {
sp.stop('Cookie file found')
nowHasCookie = true
}
})
} else {
sp.stop('Cookie file found')
nowHasCookie = true
}
} else if (!fs.existsSync(formattedCookieFile) && cookieCheckCount === 15) {
sp.stop('Cookie file not found')
p.outro(`${color.bgCyan(color.black(` Unable to download. Please add a valid and up-to-date cookies file `))}`)
process.exit(1)
} else {
cookieCheckCount += 1
if (cookieCheckCount >= 4 && cookieCheckCount < 15) sp.message('Still waiting for cookie file...')
setTimeout(checkFile, 5000)
}
}
await checkFile()
}
if (hasCookie || nowHasCookie) {
// continue with cli
}
I've tried multiple things to try and resolve this for example returning the nowHasCookie variable just in case it wasn't being set e.g. return (nowHasCookie = true). I've also tried turning the function into a setInverval and then running clearInverval when the cookie file is found. I've removed the await from the checkFile() to see if that made a difference but it doesn't. When I run the cli I get waiting for cookie, then after adding the function renames the file and displays 'cookie file found' and then quits.
It's driving me mad as I can't think what I'm doing wrong. I'd be very grateful for any help with this. Thanks for taking the time to read my post.