一、參數介紹
使用fs.stat方法獲取文件信息需要傳入文件路徑和回調函數,回調函數的參數是fs.Stats對象。
fs.Stats對象包含文件的類型、大小、修改時間、最近訪問時間等信息。
fs.stat(path, (err, stats) => {
// 處理文件信息
})
二、文件類型
通過fs.Stats對象的isFile、isDirectory、isSymbolicLink等方法可以判斷文件的類型。
isFile方法返回布爾值,表示文件是否為普通文件;
isDirectory方法返回布爾值,表示文件是否為目錄;
isSymbolicLink方法返回布爾值,表示文件是否為符號鏈接。
fs.stat(path, (err, stats) => {
if (err) throw err;
if (stats.isFile()) {
console.log('普通文件');
} else if (stats.isDirectory()) {
console.log('目錄');
} else if (stats.isSymbolicLink()) {
console.log('符號鏈接');
}
})
三、文件大小
通過fs.Stats對象的size屬性可以獲取文件的大小,單位為位元組。
fs.stat(path, (err, stats) => {
if (err) throw err;
console.log(`文件大小為${stats.size}位元組`);
})
四、文件許可權
通過fs.Stats對象的mode屬性可以獲取文件的許可權,許可權值為一個八進位數。
可以使用toString方法將八進位數轉換為對應的文件許可權字元串。
fs.stat(path, (err, stats) => {
if (err) throw err;
console.log(`文件許可權為${stats.mode.toString(8)}`);
})
五、文件時間
通過fs.Stats對象的ctime、mtime、atime屬性可以獲取文件的創建時間、修改時間、最近訪問時間。
這些屬性返回的是Date對象,可以使用toLocaleString方法將其轉換為字元串。
fs.stat(path, (err, stats) => {
if (err) throw err;
console.log(`文件創建時間為${stats.ctime.toLocaleString()}`);
console.log(`文件修改時間為${stats.mtime.toLocaleString()}`);
console.log(`文件最近訪問時間為${stats.atime.toLocaleString()}`);
})
六、完整示例代碼
const fs = require('fs');
const path = 'file.txt';
fs.stat(path, (err, stats) => {
if (err) throw err;
if (stats.isFile()) {
console.log('普通文件');
console.log(`文件大小為${stats.size}位元組`);
console.log(`文件許可權為${stats.mode.toString(8)}`);
console.log(`文件創建時間為${stats.ctime.toLocaleString()}`);
console.log(`文件修改時間為${stats.mtime.toLocaleString()}`);
console.log(`文件最近訪問時間為${stats.atime.toLocaleString()}`);
} else if (stats.isDirectory()) {
console.log('目錄');
} else if (stats.isSymbolicLink()) {
console.log('符號鏈接');
}
})
原創文章,作者:小藍,如若轉載,請註明出處:https://www.506064.com/zh-tw/n/196155.html