如何检查一个文件或目录是否存在,而不使用fs.exists?

我问的原因是因为Ubuntu上的Node.js似乎没有fs.exists()函数。 虽然我可以在我的Mac上运行Node.js时调用此方法,但是当我部署到服务器时,它会失败,并显示函数不存在。

现在,我知道有些人认为它是一个“反模式”来检查一个文件是否存在,然后尝试编辑/打开它等,但在我的情况下,我从来没有删除这些文件,但我仍然需要检查是否他们在写信给他们之前就存在了

那么如何检查目录(或文件)是否存在?

编辑:

这是我在一个名为'temp。'的文件中运行的代码:

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

在我的Mac上,它工作正常。 在Ubuntu的我得到的错误:

 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) 

在我的Mac上 – 版本:v0.13.0-pre在Ubuntu上 – 版本:v0.6.12

这可能是由于在NodeJs 0.6中exists()方法位于path模块中: http ://web.archive.org/web/20111230180637/http://nodejs.org/api/path.html – 的try-catch-终于

那个评论回答了为什么它不在那里。 我会回答你可以做些什么(除了不使用古代版本)。

fs.exists()文档 :

特别是,在打开文件之前检查文件是否存在是一种反模式,使您容易受到竞争状况的影响:另一个进程可能会在调用fs.exists()fs.open()之间删除文件。 只要打开文件,并处理不存在的错误。

你可以做这样的事情:

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

接受的答案没有考虑到节点fs模块文档build议使用fs.stat来replacefs.exists(请参阅文档 )。

我结束了这个:

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

注意ES6语法+ Promises – 同步版本会更简单一些。 另外,我的代码还检查pathstring中是否存在目录,如果stat满意,则返回true – 这可能不是每个人都想要的。

Sync方法没有任何通知有关错误的方法。 除了例外! 事实certificate,当文件或目录不存在时,fs.statSync方法会引发exception。 创build同步版本非常简单:

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

就是这样。 使用和以前一样简单:

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

[]'z