import fs from 'node:fs'; //es6
//or
const fs = require('fs'); //commonjs
/**
*
* @param {String} filePath
* @param {Number} timeout
* @returns {Promise<Boolean>}
*/
const holdBeforeFileExists = async (filePath, timeout) => {
timeout = timeout < 1000 ? 1000 : timeout
try {
var nom = 0
return new Promise(resolve => {
var inter = setInterval(() => {
nom = nom + 100
if (nom >= timeout) {
clearInterval(inter)
//maybe exists, but my time is up!
resolve(false)
}
if (fs.existsSync(filePath) && fs.lstatSync(filePath).isFile()) {
clearInterval(inter)
//clear timer, even though there's still plenty of time left
resolve(true)
}
}, 100)
})
} catch (error) {
return false
}
}
(async()=>{
const maxTimeToCheck = 3000; //3 second
const fileCreated = '/path/filename.ext';
const isFile = await holdBeforeFileExists(fileCreated, maxTimeToCheck);
//Result boolean true | false
})();
It's work goodssssssssssss................!!!
Try it before giving bad comments.
Enjoy your Kopi mana kopi obat kagak ngantuk???
express js:
router.get('some_url', async(req, res)=>{
const fileCreated = someFunctionCreateFileWithResultStringPathName();
const maxTimeToCheck = 3000; //3 second
const isFile = await holdBeforeFileExists(fileCreated, maxTimeToCheck);
if(isFile){
res.sendFile(fileCreated)
} else {
res.send('Failed to generate file, because use a bad function to generate file. or too long to create a file');
}
})