检查文件是否存在于 Gulp

Check if file exist in Gulp

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

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

可用错误代码列表 here


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.

您可以添加

var f;

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

  // ....
}

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

节点文档 does not recommend using stat to check wether a file exists:

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,简单和异步的方式是:

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

自 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.

See this answer for more details.

我相信 fs-access 包已经折旧,或者您可能想使用:

path-exists.

file-exists.

内在(path-exists):

npm install path-exists --save

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

内在(file-exists):

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 Link: path exists

NPM Link: file exists