Nodejs check file exists, if not, wait till it exist

前端 未结 7 719
一向
一向 2021-02-05 08:54

I\'m generating files automatically, and I have another script which will check if a given file is already generated, so how could I implement such a function:

f         


        
7条回答
  •  情歌与酒
    2021-02-05 09:22

    Assuming you're planning on using Promises since you did not supply a callback in your method signature, you could check if the file exists and watch the directory at the same time, then resolve if the file exists, or the file is created before the timeout occurs.

    function checkExistsWithTimeout(filePath, timeout) {
        return new Promise(function (resolve, reject) {
    
            var timer = setTimeout(function () {
                watcher.close();
                reject(new Error('File did not exists and was not created during the timeout.'));
            }, timeout);
    
            fs.access(filePath, fs.constants.R_OK, function (err) {
                if (!err) {
                    clearTimeout(timer);
                    watcher.close();
                    resolve();
                }
            });
    
            var dir = path.dirname(filePath);
            var basename = path.basename(filePath);
            var watcher = fs.watch(dir, function (eventType, filename) {
                if (eventType === 'rename' && filename === basename) {
                    clearTimeout(timer);
                    watcher.close();
                    resolve();
                }
            });
        });
    }
    

提交回复
热议问题