关于javascript:检查Gulp中是否存在文件

Check if file exist in Gulp

我需要检查gulp任务中是否存在文件,我知道我可以使用节点中的某些节点函数,有两个:

fs.exists()fs.existsSync()

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


您可以使用fs.access

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

此处列出了可用的错误代码

Using fs.access() to check for the accessibility of a file before calling fs.open(), fs.readFile() or fs.writeFile() is not recommended. Doing so introduces a race condition, since other processes may change the file's state between the two calls. Instead, user code should open/read/write the file directly and handle the error raised if the file is not accessible.


自2018年起,您可以使用fs.existsSync()

fs.exists() is deprecated, but fs.existsSync() is not. The callback parameter to fs.exists() accepts parameters that are inconsistent with other Node.js callbacks. fs.existsSync() does not use a callback.

有关详细信息,请参阅此答案。


你可以添加

1
2
3
4
5
6
7
8
9
10
11
12
var f;

try {
  var f = require('your-file');
} catch (error) {

  // ....
}

if (f) {
  console.log(f);
}

我相信fs-access包已被折旧,您可能想要使用:

path-exists

file-exists

内部(路径存在):

1
2
3
4
5
npm install path-exists --save

const myFile = '/my_file_to_ceck.html';
const exists = pathExists.sync(myFile);
console.log(exists);

内部(文件存在):

1
2
3
4
5
6
npm install file-exists --save


const fileExists = require('file-exists');
const myFile = '/my_file_to_ceck.html';
fileExists(myFile, (err, exists) => console.log(exists))

NPM链接:路径存在

NPM链接:文件存在


节点文档不建议使用stat来检查文件是否存在:

Using fs.stat() to check for the existence of a file before calling fs.open(), fs.readFile() or fs.writeFile() is not recommended.
Instead, user code should open/read/write the file directly and handle
the error raised if the file is not available.

To check if a file exists without manipulating it afterwards,
fs.access() is recommended.

如果您不需要读取或写入文件,则应使用fs.access,简单和异步方式是:

1
2
3
4
5
6
try {
    fs.accessSync(path)
    // the file exists
}catch(e){
    // the file doesn't exists
}