一、查看文件屬性
1. 常用查看文件屬性方式
const fs = require('fs')
const path = require('path')
let fileName1 = path.resolve(__dirname, './fileName1.txt')
let dirName1 = path.resolve(__dirname, './dirName1')
// 異步查看文件屬性
fs.stat(fileName1, (err, stats) => {
if (err) throw err
console.log('文件屬性:', stats)
})
fs.stat(dirName1, (err, stats) => {
if (err) throw err
console.log('文件屬性:', stats)
})
2. 語法說明
/*
* 異步查看文件屬性
* @param path {string | Buffer | URL |} 目錄名
* @param options {Object | integer}
* bigint {boolean}, 返回的 fs.stats 對象中的數值是否為 bigint 型,默認值為 false
* @param callback {Function} 回調函數
* err {Error} 查看文件屬性時拋出的錯誤
* stats {fs.Stats} 文件屬性對象
*/
fs.stat(path[, options], callback)
備注:
- 回調函數返回的
stats
是一個fs.Stats
對象
const fs = require('fs')
const path = require('path')
let dirName = path.resolve(__dirname, '../fs')
fs.stat(dirName, (err, stats) => {
console.log('stats:>> ', stats)
/*
Stats {
dev: 2483030547,
mode: 16822,
nlink: 1,
uid: 0,
gid: 0,
rdev: 0,
blksize: undefined,
ino: 48695170970944296,
size: 0,
blocks: undefined,
atimeMs: 1589769153580.5305,
mtimeMs: 1589769153580.5305,
ctimeMs: 1589769153580.5305,
birthtimeMs: 1589768320730.911,
atime: 2020-05-18T02:32:33.581Z, // 讀取文件或者執行文件時候更改
mtime: 2020-05-18T02:32:33.581Z, // 寫入文件隨文件內容的更改而更改
ctime: 2020-05-18T02:32:33.581Z, // 寫入文件,更改文件所有者,更改文件權限或者鏈接設置時更改
birthtime: 2020-05-18T02:18:40.731Z // 創建時間
}
*/
})
options
中的bigint
為true
時,數值是bigint
型而不是number
型
const fs = require('fs')
const path = require('path')
let dirName = path.resolve(__dirname, '../fs')
fs.stat(dirName, { bigint: true }, (err, stats) => {
console.log('stats:>> ', stats)
/*
Stats {
dev: 2483030547n,
mode: 16822n,
nlink: 1n,
uid: 0n,
gid: 0n,
rdev: 0n,
blksize: undefined,
ino: 48695170970944296n,
size: 0n,
blocks: undefined,
atimeMs: 1589769153580n,
mtimeMs: 1589769153580n,
ctimeMs: 1589769153580n,
birthtimeMs: 1589768320730n,
atime: 2020-05-18T02:32:33.580Z,
mtime: 2020-05-18T02:32:33.580Z,
ctime: 2020-05-18T02:32:33.580Z,
birthtime: 2020-05-18T02:18:40.730Z
}
*/
})
二、同步查看文件屬性
功能和參數與該接口的 異步 API 類似,只是參數少了 回調函數
const fs = require('fs')
fs.statSync(path[, options])
三、判斷目錄或者文件
const fs = require('fs')
const path = require('path')
let dirName = path.resolve(__dirname, '../fs')
let fileName = path.resolve(__dirname, './nodejs 寫入文件.md')
// 判斷目錄
fs.stat(dirName, (err, stats) => {
if (err) throw err
if (stats.isDirectory()) {
console.log('這是一個目錄')
}
})
// 判斷文件
fs.stat(fileName, (err, stats) => {
if (err) throw err
if (stats.isFile()) {
console.log('這是一個文件')
}
})