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

前端 未结 7 717
一向
一向 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:09

    This is very much a hack, but works for quick stuff.

    function wait (ms) {
        var now = Date.now();
        var later = now + ms;
        while (Date.now() < later) {
            // wait
        }
    }
    
    0 讨论(0)
  • 2021-02-05 09:14
    function verifyFileDownload(extension) {
        browser.sleep(150000); //waiting for file to download
        const fs = require('fs');
        let os = require('os');
        var flag = true;
        console.log(os.userInfo());
        fs.readdir('/Users/' + require("os").userInfo().username + '/Downloads/', (error, file) => {
            if (error) {
                throw error;
            }
            console.log('File name' + file);
            for (var i = 0; i < file.length; i++) {
                const fileParts = file[i].split('.');
                const ext = fileParts[fileParts.length - 1];
                if (ext === extension) {
                    flag = false;
                }
            }
            if (!flag) {
                return;
            }
            throw error;
        });
    };
    
    0 讨论(0)
  • 2021-02-05 09:17
    function holdBeforeFileExists(filePath, timeout) {
       timeout = timeout < 1000 ? 1000 : timeout;
       return new Promise((resolve)=>{  
           var timer = setTimeout(function () {
               resolve();
           },timeout);
    
           var inter = setInterval(function () {
           if(fs.existsSync(filePath) && fs.lstatSync(filePath).isFile()){
               clearInterval(inter);
               clearTimeout(timer);
               resolve();
           }
         }, 100);
      });
    }
    
    0 讨论(0)
  • 2021-02-05 09:20

    fs.watch() API is what you need.

    Be sure to read all the caveats mentioned there before you use it.

    0 讨论(0)
  • 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();
                }
            });
        });
    }
    
    0 讨论(0)
  • 2021-02-05 09:26

    Here is the solution:

    // Wait for file to exist, checks every 2 seconds
    function getFile(path, timeout) {
        const timeout = setInterval(function() {
    
            const file = path;
            const fileExists = fs.existsSync(file);
    
            console.log('Checking for: ', file);
            console.log('Exists: ', fileExists);
    
            if (fileExists) {
                clearInterval(timeout);
            }
        }, timeout);
    };
    
    0 讨论(0)
提交回复
热议问题