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)。非經特殊聲明,原始代碼版權歸原作者所有,本譯文未經允許或授權,請勿轉載或複製。