NodeJS:检查文件是否存在且可读(fs.exists() 替代方案)
这是在 Node.js 中检查文件是否存在且可读的最佳函数。它是已弃用的 fs.exists() 函数的替代方案。
纯 Javascript:
fileExists.js
const fs = require('fs').promises;
async function fileExistsAndIsReadable(path) {
try {
await fs.access(path, fs.constants.F_OK | fs.constants.R_OK);
return true;
} catch (err) {
return false;
}
}或使用 TypeScript:
fileExists.ts
import { access, constants } from 'fs/promises';
import { PathLike } from 'fs';
export async function fileExistsAndIsReadable(path: PathLike): Promise<boolean> {
try {
await access(path, constants.F_OK | constants.R_OK);
return true;
} catch (err) {
return false;
}
}用法示例:
fileExists_usage.js
// Usage example:
const path = 'path/to/your/file.txt';
fileExistsAndIsReadable(path)
.then((result) => {
if (result) {
console.log('File exists and is readable');
} else {
console.log('File does not exist or is not readable');
}
})
.catch((err) => {
console.error('An unexpected error occurred', err);
});Check out similar posts by category:
NodeJS
If this post helped you, please consider buying me a coffee or donating via PayPal to support research & publishing of new posts on TechOverflow