检查Gulp

时间:2015-05-20 11:49:48

标签: javascript node.js gulp

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

fs.exists()fs.existsSync()

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

5 个答案:

答案 0 :(得分:40)

您可以使用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

  

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

答案 1 :(得分:2)

你可以添加

var f;

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

  // ....
}

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

答案 2 :(得分:0)

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

  

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

     

要检查文件是否存在而不进行操作,   建议使用fs.access()。

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

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

答案 3 :(得分:0)

截至2018年,您可以使用fs.existsSync()

  不建议使用

fs.exists(),但不建议使用fs.existsSync()。 fs.exists()的回调参数接受与其他Node.js回调不一致的参数。 fs.existsSync()不使用回调。

See this answer for more details.

答案 4 :(得分:0)

我认为fs-access包已被贬值,或者您可能想使用:

path-exists

file-exists

内tra(存在路径):

npm install path-exists --save

const myFile = '/my_file_to_ceck.html';
const exists = pathExists.sync(myFile);
console.log(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

相关问题