检查Gulp中是否存在文件

我需要检查一个文件是否存在于一个吞吐任务中,我知道我可以使用节点的一些节点function,有两个:

fs.exists()fs.existsSync()

问题是在节点文档中,是说这些函数将被弃用

你可以使用fs.access

 fs.access('/etc/passwd', (err) => { if (err) { // file/path is not visible to the calling process console.log(err.message); console.log(err.code); } }); 

这里列出可用的错误代码


在调用fs.open(), fs.readFile()之前使用fs.access()检查文件的可访问性,不build议使用fs.open(), fs.readFile()fs.writeFile() 。 这样做会引入争用条件,因为其他进程可能会更改两个调用之间的文件状态。 相反,用户代码应直接打开/读取/写入文件,并处理文件不可访问时引发的错误。

你可以添加

 var f; try { var f = require('your-file'); } catch (error) { // .... } if (f) { console.log(f); } 

节点documentatión 不build议使用stat来检查文件是否存在 :

在调用fs.open()之前使用fs.stat()检查文件是否存在,不推荐使用fs.readFile()或fs.writeFile()。 相反, 用户代码应直接打开/读取/写入文件,并处理文件不可用时引发的错误

要检查一个文件是否存在,而没有后来操作,build议使用fs.access()。

如果你不需要读或写文件你应该使用fs.access ,简单和asynchronous的方式是:

 try { fs.accessSync(path) // the file exists }catch(e){ // the file doesn't exists }