Node.js 檔案狀態
每個檔案都有一組我們可以使用 Node.js 檢查的詳細資訊。特別是,可以使用 fs 模組 提供的 stat() 方法。
你呼叫它並傳入一個檔案路徑,一旦 Node.js 獲取到檔案詳細資訊,它就會呼叫你傳入的回撥函式,該函式有兩個引數:一個錯誤訊息和檔案狀態資訊。
const = ('node:fs');
.('/Users/joe/test.txt', (, ) => {
if () {
.();
}
// we have access to the file stats in `stats`
});
Node.js 還提供了一個同步方法,它會阻塞執行緒直到檔案狀態資訊準備就緒。
const = ('node:fs');
try {
const = .('/Users/joe/test.txt');
} catch () {
.();
}
檔案資訊包含在 stats 變數中。我們可以使用 stats 提取什麼樣的資訊?
很多,包括:
- 使用
stats.isFile()和stats.isDirectory()判斷該路徑是檔案還是目錄。 - 使用
stats.isSymbolicLink()判斷該路徑是否為符號連結。 - 使用
stats.size獲取檔案大小(以位元組為單位)。
還有其他一些高階方法,但你在日常程式設計中會用到的大部分就是這些。
const = ('node:fs');
.('/Users/joe/test.txt', (, ) => {
if () {
.();
return;
}
.(); // true
.(); // false
.(); // false
.(.); // 1024000 //= 1MB
});
如果你願意,也可以使用 fs/promises 模組提供的基於 promise 的 fsPromises.stat() 方法。
const = ('node:fs/promises');
async function () {
try {
const = await .('/Users/joe/test.txt');
.(); // true
.(); // false
.(); // false
.(.); // 1024000 //= 1MB
} catch () {
.();
}
}
();
你可以在官方文件中閱讀更多關於 fs 模組的資訊。