如何在创build之前保证文件不存在?
fs.exists
现在已经被弃用了一个体面的原因,我应该尝试打开一个文件,并捕获错误,以确保在检查和打开之间没有任何可能删除文件。 但是,如果我需要创build一个新文件而不是打开一个现有的文件,我怎么保证没有文件,然后我尝试创build它?
你不能。 但是,您可以创build一个新文件或打开一个现有的文件
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+"
打开它,如果它已经存在,将会出错,让你处理错误。
module.exports = fs.existsSync || function existsSync(filePath){ try{ fs.statSync(filePath); }catch(err){ if(err.code == 'ENOENT') return false; } return true; };
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 } } );