fs.promise.lstat()方法在Node.js的文件係統模塊中定義。文件係統模塊本質上是用於與用戶計算機的硬盤進行交互的。 lstat()方法使用在stats對象(lstat提供的數據)上定義的方法,提供了一些特定於文件和文件夾的信息。 fs.promise.lstat()方法返回已解決或被拒絕的Promise,因此避免了fs.readdir()方法中可能發生的回調嵌套或回調地獄問題。
用法
fs.promise.lstat(path, options)
參數:該方法接受上述和以下所述的兩個參數:
path:它是一個字符串,緩衝區或url,用於指定目錄的路徑,我們嘗試讀取其內容。
options:它是一個可選參數。一個選項參數是‘bigint’,它是一個布爾值。在這裏,我們通過fs.lstat()方法指定返回的統計對象中的數值是否為bigint(default-false)。
返回值:它返回已解決或已拒絕的承諾。如果成功讀取目錄,則使用stats對象解析promise,否則,如果發生任何錯誤(example-specified目錄不存在或沒有讀取文件的權限,則使用錯誤對象),則拒絕該對象。
從已解決的promise返回的stats對象中定義了一些屬性和方法,這些屬性和方法有助於獲取有關目標文件或文件夾的某些特定詳細信息。下麵指定了一些方法。
- stats.isDirectory():如果stats對象描述文件係統目錄,則返回true。
- stats.isFile():如果stats對象描述一個常規文件,則返回true。
- stats.isSocket():如果stats對象描述一個套接字,則返回true。
- stats.isSymbolicLink():如果stats對象描述符號鏈接,則返回true。
- stats.isFile():如果stats對象描述一個常規文件,則返回true。
- stats.isFIFO():如果stats對象描述先進先出管道,則返回true。
- stats.size:指定文件大小(以字節為單位)。
- stats.blocks:指定為文件分配的塊數。
範例1:
// Node.js program to demonstrate the
// Buffer.from() Method
// Importing File System module
const fs = require('fs')
// fs.readdir() reads contents of
// target directory
// process.cwd() gives current
// working directory
fs.readdir(process.cwd(), (err, filenames) => {
if (err) {
console.log(err)
return
}
for (let filename of filenames) {
// Calling lstat method to give the
// stats object for every directory
fs.promises.lstat(filename)
// If promise resolved and datas
// are fetched
.then(stats => {
if (stats.isFile()) {
console.log(`${filename} ---------> File`)
} else {
console.log(`${filename} ---------> Folder`)
}
})
// If promise is rejected
.catch(err => {
console.log(err)
})
}
})
輸出:
範例2:
// Node.js program to demonstrate the
// Buffer.from() Method
// Importing File System module
const fs = require('fs')
// The fs.readdir() method reads the
// contents of target directory
// The process.cwd() method gives the
// current working directory
fs.readdir(process.cwd(), async (err, filenames) => {
if (err) {
console.log(err)
return
}
for (let filename of filenames) {
// Calling lstat method to give the
// stats object for every directory
fs.promises.lstat(filename)
// If promise resolved and datas
// are fetched
.then(stats => {
console.log(
`${filename} --------> ${stats.size} bytes`)
})
// If promise is rejected
.catch(err => {
console.log(err)
})
}
})
輸出:
參考: https://nodejs.org/api/fs.html#fs_fspromises_lstat_path_options
相關用法
- Node.js console.timeLog()用法及代碼示例
- Node.js GM shave()用法及代碼示例
- Node.js GM emboss()用法及代碼示例
- Node.js GM crop()用法及代碼示例
- Node.js GM despeckle()用法及代碼示例
- Node.js GM whiteThreshold()用法及代碼示例
- Node.js GM whitePoint()用法及代碼示例
- Node.js GM border()用法及代碼示例
- Node.js GM solarize()用法及代碼示例
- Node.js GM motionBlur()用法及代碼示例
- Node.js GM magnify()用法及代碼示例
- Node.js GM minify()用法及代碼示例
- Node.js GM write()用法及代碼示例
注:本文由純淨天空篩選整理自hunter__js大神的英文原創作品 Node.js | fsPromise.lstat() Method。非經特殊聲明,原始代碼版權歸原作者所有,本譯文未經允許或授權,請勿轉載或複製。