fs.exists(path, callback)
历史
版本 | 变化 |
---|---|
v18.0.0 | 将无效回调传递给 |
v7.6.0 |
|
v1.0.0 | 弃用自:v1.0.0 |
v0.0.2 | 添加于:v0.0.2 |
Stability: 0 - 已弃用:改用
fs.stat()
或 fs.access()
。参数
path
<string> | <Buffer> | <URL>callback
<Function>exists
<boolean>
通过检查文件系统来测试给定路径是否存在。然后使用 true 或 false 调用 callback
参数:
import { exists } from 'node:fs';
exists('/etc/passwd', (e) => {
console.log(e ? 'it exists' : 'no passwd!');
});
此回调的参数与其他 Node.js 回调不一致。通常,Node.js 回调的第一个参数是 err
参数,后面可以选择其他参数。 fs.exists()
回调只有一个布尔参数。这是推荐使用 fs.access()
而不是 fs.exists()
的原因之一。
不建议在调用 fs.open()
、 fs.readFile()
或 fs.writeFile()
之前使用 fs.exists()
检查文件是否存在。这样做会引入竞争条件,因为其他进程可能会在两次调用之间更改文件的状态。相反,用户代码应该直接打开/读取/写入文件并处理文件不存在时引发的错误。
写(不推荐)
import { exists, open, close } from 'node:fs';
exists('myfile', (e) => {
if (e) {
console.error('myfile already exists');
} else {
open('myfile', 'wx', (err, fd) => {
if (err) throw err;
try {
writeMyData(fd);
} finally {
close(fd, (err) => {
if (err) throw err;
});
}
});
}
});
写(推荐)
import { open, close } from 'node:fs';
open('myfile', 'wx', (err, fd) => {
if (err) {
if (err.code === 'EEXIST') {
console.error('myfile already exists');
return;
}
throw err;
}
try {
writeMyData(fd);
} finally {
close(fd, (err) => {
if (err) throw err;
});
}
});
阅读(不推荐)
import { open, close, exists } from 'node:fs';
exists('myfile', (e) => {
if (e) {
open('myfile', 'r', (err, fd) => {
if (err) throw err;
try {
readMyData(fd);
} finally {
close(fd, (err) => {
if (err) throw err;
});
}
});
} else {
console.error('myfile does not exist');
}
});
阅读(推荐)
import { open, close } from 'node:fs';
open('myfile', 'r', (err, fd) => {
if (err) {
if (err.code === 'ENOENT') {
console.error('myfile does not exist');
return;
}
throw err;
}
try {
readMyData(fd);
} finally {
close(fd, (err) => {
if (err) throw err;
});
}
});
上面的"not recommended" 示例检查是否存在,然后使用该文件; "recommended" 示例更好,因为它们直接使用文件并处理错误(如果有)。
通常,仅当文件不会被直接使用时才检查文件是否存在,例如当它的存在是来自另一个进程的信号时。
相关用法
- Node.js fs.exists()用法及代码示例
- Node.js fs.existsSync()用法及代码示例
- Node.js fs.existsSync(path)用法及代码示例
- Node.js fs.extra ensureDir()用法及代码示例
- Node.js fs.filehandle.datasync()用法及代码示例
- Node.js fs.chmod()用法及代码示例
- Node.js fs.read()用法及代码示例
- Node.js fs.Dirent.isFile()用法及代码示例
- Node.js fs.Dir.closeSync()用法及代码示例
- Node.js fs.fchmodSync()用法及代码示例
- Node.js fs.symlink(target, path[, type], callback)用法及代码示例
- Node.js fs.constants用法及代码示例
- Node.js fs.mkdir()用法及代码示例
- Node.js fs.mkdirSync()用法及代码示例
- Node.js fs.fdatasync()用法及代码示例
- Node.js fs.Dirent.isFIFO()用法及代码示例
- Node.js fs.copyFile()用法及代码示例
- Node.js fs.writeSync()用法及代码示例
- Node.js fs.symlink()用法及代码示例
- Node.js fs.truncate()用法及代码示例
- Node.js fs.openSync()用法及代码示例
- Node.js fs.filehandle.write()用法及代码示例
- Node.js fs.fdatasyncSync()用法及代码示例
- Node.js fs.filehandle.sync()用法及代码示例
- Node.js fs.fsyncSync()用法及代码示例
注:本文由纯净天空筛选整理自nodejs.org大神的英文原创作品 fs.exists(path, callback)。非经特殊声明,原始代码版权归原作者所有,本译文未经允许或授权,请勿转载或复制。