如何检查文件是否存在?
当前回答
现代异步/等待方式(Node 12.8. net)。x)
const fileExists = async path => !!(await fs.promises.stat(path).catch(e => false));
const main = async () => {
console.log(await fileExists('/path/myfile.txt'));
}
main();
我们需要使用fs.stat()或fs.access(),因为fs。Exists (path, callback)现在已弃用
另一个好方法是fs-extra
其他回答
fs.statSync(path, function(err, stat){
if(err == null) {
console.log('File exists');
//code when all ok
}else if (err.code == "ENOENT") {
//file doesn't exist
console.log('not file');
}
else {
console.log('Some other error: ', err.code);
}
});
现代异步/等待方式(Node 12.8. net)。x)
const fileExists = async path => !!(await fs.promises.stat(path).catch(e => false));
const main = async () => {
console.log(await fileExists('/path/myfile.txt'));
}
main();
我们需要使用fs.stat()或fs.access(),因为fs。Exists (path, callback)现在已弃用
另一个好方法是fs-extra
一种更简单的同步方法。
if (fs.existsSync('/etc/file')) {
console.log('Found file');
}
API文档说明了existsSync是如何工作的: 通过检查文件系统来测试给定路径是否存在。
编辑: 从节点v10.0.0开始,我们可以使用fs.promises.access(…)
检查文件是否存在的异步代码示例:
function checkFileExists(file) {
return fs.promises.access(file, fs.constants.F_OK)
.then(() => true)
.catch(() => false)
}
stat的替代方法可能是使用新的fs.access(…):
简化的短承诺函数检查:
s => new Promise(r=>fs.access(s, fs.constants.F_OK, e => r(!e)))
示例用法:
let checkFileExists = s => new Promise(r=>fs.access(s, fs.constants.F_OK, e => r(!e)))
checkFileExists("Some File Location")
.then(bool => console.log(´file exists: ${bool}´))
扩大承诺方式:
// returns a promise which resolves true if file exists:
function checkFileExists(filepath){
return new Promise((resolve, reject) => {
fs.access(filepath, fs.constants.F_OK, error => {
resolve(!error);
});
});
}
或者如果你想同步操作:
function checkFileExistsSync(filepath){
let flag = true;
try{
fs.accessSync(filepath, fs.constants.F_OK);
}catch(e){
flag = false;
}
return flag;
}
2021年8月
读完所有帖子后:
let filePath = "./directory1/file1.txt";
if (fs.existsSync(filePath)) {
console.log("The file exists");
} else {
console.log("The file does not exist");
}
推荐文章
- 有没有办法修复包锁。json lockfileVersion所以npm使用特定的格式?
- 如何使用npm全局安装一个模块?
- 实时http流到HTML5视频客户端的最佳方法
- 使用node.js下载图像
- Node.js Express中的HTTP GET请求
- Node.js:将文本文件读入数组。(每一行都是数组中的一项。)
- npm犯错!错误:EPERM:操作不允许,重命名
- Node Sass还不支持当前环境:Linux 64位,带false
- 我如何添加环境变量启动。VSCode中的json
- 解析错误:无法读取文件“…/tsconfig.json”.eslint
- 在Node.js中'use strict'语句是如何解释的?
- 当WebSockets可用时,为什么要使用AJAX ?
- 使用过程。TypeScript中的env
- 如何找到哪些承诺未处理在Node.js UnhandledPromiseRejectionWarning?
- 如何卸载Yarn