在Node.js的文件係統模塊中定義的fs.promise.readdir()方法。文件係統模塊本質上是用於與用戶計算機的硬盤進行交互的。 readdir()方法用於讀取文件和文件夾的名稱。 fs.promise.readdir()方法返回已解決或拒絕的承諾,因此避免了fs.readdir()方法中可能發生的回調嵌套或回調地獄問題。
用法
fs.promise.readdir(path, options)
參數:該方法接受上述和以下所述的兩個參數:
- path:它是一個字符串,緩衝區或url,它指定要讀取其內容的目錄的路徑。
- options:它是一個可選參數,用於指定編碼技術(default-utf8)等。
返回值:它返回已解決或已拒絕的承諾。如果成功讀取目錄,則使用文件和文件夾的名稱列表來解決承諾;如果發生任何錯誤(example-specified目錄不存在或沒有讀取文件的權限等),則通過錯誤對象拒絕該承諾。
範例1:
// Node.js program to demonstrate the
// fs.promise.readdir() Method
// Importing File System module
const fs = require('fs')
// The process.cwd() gives current
// working directory
fs.promises.readdir(process.cwd())
// If promise resolved and
// datas are fetched
.then(filenames => {
for (let filename of filenames) {
console.log(filename)
}
})
// If promise is rejected
.catch(err => {
console.log(err)
})
輸出:閱讀並顯示當前工作目錄“ gfgExamples”的內容
範例2:
// Node.js program to demonstrate the
// fs.promise.readdir() Method
// Importing File System module
const fs = require('fs')
// process.cwd() gives current
// working directory
const targetDir = process.argv[2] || process.cwd()
fs.promises.readdir(targetDir)
// If promise resolved and
// datas are fetched
.then(filenames => {
for (let filename of filenames) {
console.log(filename)
}
})
// If promise is rejected
.catch(err => {
console.log(err)
})
輸出:讀取並顯示一個目錄的內容,並返回到當前工作目錄“ gfgExamples”。
參考: https://nodejs.org/docs/latest/api/fs.html#fs_fspromises_readdir_path_options
相關用法
- Node.js console.timeLog()用法及代碼示例
- Node.js GM transparent()用法及代碼示例
- Node.js GM drawRectangle()用法及代碼示例
- Node.js GM orderedDither()用法及代碼示例
- Node.js GM paint()用法及代碼示例
- Node.js GM spread()用法及代碼示例
- Node.js GM flip()用法及代碼示例
- Node.js GM roll()用法及代碼示例
- Node.js GM thumbnail()用法及代碼示例
- Node.js GM threshold()用法及代碼示例
- Node.js GM whitePoint()用法及代碼示例
- Node.js GM whiteThreshold()用法及代碼示例
- Node.js GM segment()用法及代碼示例
- Node.js GM quality()用法及代碼示例
注:本文由純淨天空篩選整理自hunter__js大神的英文原創作品 Node.js | fs.promise.readdir() Method。非經特殊聲明,原始代碼版權歸原作者所有,本譯文未經允許或授權,請勿轉載或複製。