2015-09-27 22 views
2

fs.exists现在不推荐使用,因为我应该尝试打开文件并捕获错误,以确保无法在检查和打开之间删除文件。但是如果我需要创建一个新文件而不是打开现有文件,那么在我尝试创建它之前,如何保证没有文件?如何在创建之前保证文件不存在?

回答

1

你不能。但是,您可以创建一个新的文件打开一个现有的,如果它存在:

fs.open("/path", "a+", function(err, data){ // open for reading and appending 
    if(err) return handleError(err); 
    // work with file here, if file does not exist it will be created 
}); 

或者,"ax+"打开它,如果它已经存在,这将报错,让你处理错误。

0
module.exports = fs.existsSync || function existsSync(filePath){ 
    try{ 
    fs.statSync(filePath); 
    }catch(err){ 
    if(err.code == 'ENOENT') return false; 
    } 
    return true; 
}; 

https://gist.github.com/FGRibreau/3323836

0

https://stackoverflow.com/a/31545073/2435443

fs = require('fs') ; 
var path = 'sth' ; 
fs.stat(path, function(err, stat) { 
    if (err) { 
     if ('ENOENT' == err.code) { 
      //file did'nt exist so for example send 404 to client 
     } else { 
      //it is a server error so for example send 500 to client 
     } 
    } else { 
     //every thing was ok so for example you can read it and send it to client 
    } 
}); 
相关问题