我正在尝试在 Node.js 中编写一个简单的函数来检查文件系统条目是否存在,它可以是任何类型的条目,包括:
我想得到 FALSE 的唯一情况是文件系统条目根本不存在。
我无法使用
fs.existsSync()
- 因为这对于现有的损坏的符号链接失败:https://github.com/nodejs/node/issues/14025
fs.readdirSync()
),因为在这种情况下这是一个非常昂贵的操作。正如 Colin D 所指出的,您可以使用 lstat,它不会解析符号链接。但是,您将无法避免捕获异常或使用异步代码。
import { lstat } from 'fs/promises'
const exists = path => lstat(path).then(() => true, () => false)
if (await exists('file_or_link')) {
// exists
} else {
// does not exist
}
如果您想要抛出除存在之外的其他错误:
async function exists(path) {
try {
await lstat(path)
return true
} catch (err) {
if (err.code !== 'EEXIST') throw err
return false
}
}
同样同步:
const { lstatSync } = require('fs')
function existsSync(path) {
try {
lstatSync(path)
return true
} catch (err) {
if (err.code !== 'EEXIST') throw err
return false
}
}
否则,您可以使用 NAPI 编写本机附加组件,以实现您在 C/C++ 中所需的功能。