2014-10-02 14 views
7

sto generazione automatica di file, e ho un altro script che controllerà se un dato file è già generato, così come potrei implementare tale funzione:Nodejs controllo del file esiste, se non, aspettare che esiste

function checkExistsWithTimeout(path, timeout) 

che verificherà se esiste un percorso, in caso contrario, attendere, utilizzare timeout.

+1

Quale sistema operativo stai prendendo di mira? Su Linux/OSX puoi fare in modo che Node.js guardi una directory per le modifiche. – Brad

+0

Sto eseguendo il codice su Linux – wong2

+2

questo potrebbe essere utile; http://nodejs.org/docs/latest/api/fs.html#fs_fs_watchfile_filename_options_listener – renatoargh

risposta

0

fs.watch() API è ciò di cui hai bisogno.

Assicurati di leggere tutti i avvertimenti indicati prima di usarlo.

+1

Non lo trovo così utile come fs.watch sembra aver bisogno che il file esista prima che possa essere visto ... –

0

Questo è molto un hack, ma funziona per cose veloci.

function wait (ms) { 
    var now = Date.now(); 
    var later = now + ms; 
    while (Date.now() < later) { 
     // wait 
    } 
} 
0

ecco la soluzione:

// 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

si potrebbe implementare in questo modo se si dispone di nodo 6 o superiore.

const fs = require('fs') 

function checkExistsWithTimeout(path, timeout) { 
    return new Promise((resolve, reject) => { 
    const timeoutTimerId = setTimeout(handleTimeout, timeout) 
    const interval = timeout/6 
    let intervalTimerId 

    function handleTimeout() { 
     clearTimeout(timerId) 

     const error = new Error('path check timed out') 
     error.name = 'PATH_CHECK_TIMED_OUT' 
     reject(error) 
    } 

    function handleInterval() { 
     fs.access(path, (err) => { 
     if(err) { 
      intervalTimerId = setTimeout(handleInterval, interval) 
     } else { 
      clearTimeout(timeoutTimerId) 
      resolve(path) 
     } 
     }) 
    } 

    intervalTimerId = setTimeout(handleInterval, interval) 
    }) 
} 
0

Supponendo che si sta pensando di usare Promises in quanto non è stato fornire una richiamata nella vostra firma del metodo, si potrebbe verificare l'esistenza del file e guardare la directory, allo stesso tempo, quindi risolvere se il file esiste, o il file viene creato prima che si verifichi il timeout.

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(); 
      } 
     }); 
    }); 
}