【发布时间】:2023-03-29 16:45:01
【问题描述】:
我需要检查 gulp 任务中是否存在文件,我知道我可以使用 node 中的一些 node 函数,有两个:
fs.exists() 和 fs.existsSync()
问题是在节点文档中,说这些功能将被弃用
【问题讨论】:
标签: javascript node.js gulp
我需要检查 gulp 任务中是否存在文件,我知道我可以使用 node 中的一些 node 函数,有两个:
fs.exists() 和 fs.existsSync()
问题是在节点文档中,说这些功能将被弃用
【问题讨论】:
标签: javascript node.js gulp
我相信fs-access 包已经贬值,或者你可能想使用:
path-exists.
file-exists.
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))
【讨论】:
截至2018年,您可以使用fs.existsSync():
fs.exists() 已弃用,但 fs.existsSync() 不是。 fs.exists() 的回调参数接受与其他 Node.js 回调不一致的参数。 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
不建议在调用
fs.open(), fs.readFile()或fs.writeFile()之前使用fs.access()检查文件的可访问性。这样做会引入竞争条件,因为其他进程可能会在两次调用之间更改文件的状态。相反,用户代码应该直接打开/读取/写入文件并处理文件不可访问时引发的错误。
【讨论】:
节点文档does not recommend using stat to check wether a file exists:
不建议在调用 fs.open()、fs.readFile() 或 fs.writeFile() 之前使用 fs.stat() 检查文件是否存在。 相反,用户代码应该直接打开/读取/写入文件并处理 如果文件不可用,则会引发错误。
要检查文件是否存在而不随后对其进行操作, 推荐使用 fs.access()。
如果你不需要读写文件你应该使用fs.access,简单的异步方式是:
try {
fs.accessSync(path)
// the file exists
}catch(e){
// the file doesn't exists
}
【讨论】:
你可以添加
var f;
try {
var f = require('your-file');
} catch (error) {
// ....
}
if (f) {
console.log(f);
}
【讨论】: