js 检测文件路径是否存在
时间: 2023-09-13 09:09:16 浏览: 89
在 JavaScript 中,可以使用异步的文件系统 API 来检测文件路径是否存在。以下是一个示例代码,展示了如何使用 Node.js 的 fs 模块来检测文件路径是否存在:
```javascript
const fs = require('fs');
function checkPathExists(path) {
return new Promise((resolve) => {
fs.access(path, fs.constants.F_OK, (error) => {
if (error) {
resolve(false); // 文件路径不存在
} else {
resolve(true); // 文件路径存在
}
});
});
}
// 调用示例
const filePath = '/path/to/file.txt';
checkPathExists(filePath)
.then((exists) => {
if (exists) {
console.log('文件路径存在');
} else {
console.log('文件路径不存在');
}
})
.catch((error) => console.error(error));
```
在上述示例中,`checkPathExists` 函数接受一个文件路径作为参数,并返回一个 Promise 对象。它使用 `fs.access` 方法来检查文件路径是否存在。如果文件路径存在,回调函数中的 `error` 参数将为 `null`,否则将包含错误信息。根据是否存在错误,我们可以确定文件路径是否存在。
请注意,这是一个基于 Node.js 的示例,如果你需要在浏览器环境中检测文件路径是否存在,将需要使用不同的方法和 API。