2014-12-14 14 views
5

Il motivo per cui lo chiedo è perché Node.js su ubuntu non sembra avere la funzione fs.exists(). Anche se posso richiamarlo quando eseguo Node.js sul mio Mac, quando eseguo il deploy sul server, fallisce con un errore che dice che la funzione non esiste.Come verificare se esiste un file o una directory senza utilizzare fs.exists?

Ora, sono consapevole che alcune persone considerano un "anti-pattern" per verificare se esiste un file e quindi provare a modificarlo/aprirlo, ecc., Ma nel mio caso, non ho mai cancellato questi file, ma continuo a è necessario verificare se esistono prima di scriverli.

Quindi, come posso verificare se la directory (o il file) esiste?

EDIT:

Questo è il codice corro in un file chiamato 'temp.':

var fs=require('fs'); 
fs.exists('./temp.js',function(exists){ 
    if(exists){ 
     console.log('yes'); 
    }else{ 
     console.log("no"); 
    } 
}); 

Sul mio Mac, funziona benissimo. Su Ubuntu ottengo l'errore:

node.js:201 
     throw e; // process.nextTick error, or 'error' event on first tick 
      ^TypeError: Object #<Object> has no method 'exists' 
    at Object.<anonymous> (/home/banana/temp.js:2:4) 
    at Module._compile (module.js:441:26) 
    at Object..js (module.js:459:10) 
    at Module.load (module.js:348:32) 
    at Function._load (module.js:308:12) 
    at Array.0 (module.js:479:10) 
    at EventEmitter._tickCallback (node.js:192:41) 

Sul mio Mac - Versione: v0.13.0-pre Su Ubuntu - Versione: v0.6.12

+1

La tua domanda è sbagliata, si deve andare "Perché fs.exists() manca?". Potresti aggiungere quali versioni di NodeJs hai sul tuo PC e Mac? Che errore ottieni? Qualcosa come "esiste non è una funzione"? Altri metodi FS tipici mancano su quell'oggetto 'fs'? Come si richiede 'fs'? –

+0

Sto usando Ubuntu e il tuo codice funziona bene per me. Quindi è un problema sulla tua macchina specifica. Come hai installato il nodo? Quale versione di Node e Ubuntu stai usando? –

+2

Probabilmente è dovuto al fatto che in NodeJs 0.6 il metodo 'exists()' era situato nel modulo 'path': http://web.archive.org/web/20111230180637/http://nodejs.org/api /path.html –

risposta

7

It's probably due to the fact that in NodeJs 0.6 the exists() method was located in the path module: http://web.archive.org/web/20111230180637/http://nodejs.org/api/path.htmltry-catch-finally

^^ quel commento risposte perché esso isn' Là. Risponderò a ciò che puoi fare al riguardo (oltre a non usare versioni antiche).

Dal fs.exists() documentation:

In particular, checking if a file exists before opening it is an anti-pattern that leaves you vulnerable to race conditions: another process may remove the file between the calls to fs.exists() and fs.open() . Just open the file and handle the error when it's not there.

Si potrebbe fare qualcosa di simile:

fs.open('mypath','r',function(err,fd){ 
    if (err && err.code=='ENOENT') { /* file doesn't exist */ } 
}); 
6

La risposta accettata non tiene conto del fatto che la documentazione del modulo fs nodo consiglia di utilizzare per sostituire fs.stat fs.exists (vedi the documentation).

ho finito per andare con questo:

function filePathExists(filePath) { 
    return new Promise((resolve, reject) => { 
    fs.stat(filePath, (err, stats) => { 
     if (err && err.code === 'ENOENT') { 
     return resolve(false); 
     } else if (err) { 
     return reject(err); 
     } 
     if (stats.isFile() || stats.isDirectory()) { 
     return resolve(true); 
     } 
    }); 
    }); 
} 

Nota ES6 sintassi + Promesse - la versione di sincronizzazione di questo sarebbe un po 'più semplice. Inoltre, il mio codice controlla anche se è presente una directory nella stringa del percorso e restituisce true se stat è soddisfatta: potrebbe non essere ciò che tutti vogliono.

0

I metodi di sincronizzazione non hanno alcun modo di notificare un errore. Tranne le eccezioni! Come risulta, il metodo fs.statSync genera un'eccezione quando il file o la directory non esiste. La creazione della versione di sincronizzazione è semplice:

function checkDirectorySync(directory) { 
    try { 
    fs.statSync(directory); 
    } catch(e) {  
    try { 
     fs.mkdirSync(directory); 
    } catch(e) { 
     return e; 
    } 
    } 
} 

E questo è tutto. Utilizzando è semplice come prima:

checkDirectorySync("./logs"); 
//directory created/exists, all good. 

[]'z

Problemi correlati