Node.js fs
本地模块提供了几种有用的方法,可用于处理目录。 检查Node.js中是否存在某个目录的最简单方法是使用fs.existsSync()
方法。
existSync()
方法同步检查给定目录的存在。 这是一个例子:
const fs = require('fs');
// directory to check if exists
const dir = './uploads';
// check if directory exists
if (fs.existsSync(dir)) {
console.log('Directory exists!');
} else {
console.log('Directory not found.');
}
如果路径存在,则existSync()
方法返回true
,否则返回false
。
如果您更喜欢使用异步检查,请改用fs.access()
方法。 此方法将路径作为输入并测试用户的权限。
让我们看下面的示例,该示例使用fs.access()
检查给定目录是否存在:
const fs = require('fs');
// directory to check if exists
const dir = './uploads';
// check if directory exists
fs.access(dir, (err) => {
console.log(`Directory ${err ? 'does not exist' : 'exists'}`);
});
查看本指南,以了解有关在Node.js应用程序中读写文件的更多信息。
扫码关注腾讯云开发者
领取腾讯云代金券
Copyright © 2013 - 2025 Tencent Cloud. All Rights Reserved. 腾讯云 版权所有
深圳市腾讯计算机系统有限公司 ICP备案/许可证号:粤B2-20090059 深公网安备号 44030502008569
腾讯云计算(北京)有限责任公司 京ICP证150476号 | 京ICP备11018762号 | 京公网安备号11010802020287
Copyright © 2013 - 2025 Tencent Cloud.
All Rights Reserved. 腾讯云 版权所有