當前位置: 首頁>>代碼示例 >>用法及示例精選 >>正文


Node.js fsPromises.opendir()用法及代碼示例


fsPromises.opendir()方法在Node.js的文件係統模塊中定義。文件係統模塊本質上是用於與用戶計算機的硬盤進行交互的。該方法用於異步打開目錄。

fsPromise.opendir()方法返回已解決或被拒絕的諾言,因此避免了fs.opendir()中可能發生的回調嵌套或回調地獄問題。承諾通過“ fs.Dir”對象解析,該對象本身包含其他用於訪問和關閉目錄的函數。如果諾言被拒絕,它將被錯誤對象拒絕。

用法:

fs.promises.opendir(path, options)

參數:該方法接受上述和以下所述的兩個參數:

  • path:它是一個String,Buffer或Url,它指定必須打開的目錄的路徑。
  • options:它是一個可選參數,它會以某種方式影響輸出,因此會相應地將其提供給函數調用。
    • encoding:它指定了編碼技術,默認為“ UTF8”
    • bufferSize:它是一個數字,指定當從目錄讀取時在內部緩衝的目錄條目的數量。 bufferSize的值較高,可以確保良好的性能,但會導致更多的內存使用。

返回值:該方法返回一個用“ fs.Dir”對象解析的promise,該對象本身包含其他用於訪問和關閉目錄的函數。如果諾言被拒絕,它將被錯誤對象拒絕。



‘dir’對象方法:

  • dir.close()方法:它異步關閉目錄的資源,因此,後續嘗試讀取將導致錯誤。返回一個Promise,將在資源關閉後解決。
  • dir.closeSync()方法:它同步關閉目錄的資源,因此,後續嘗試讀取將導致錯誤。
  • dir.path:返回目錄的路徑。
  • dir.read()方法:它異步讀取下一個目錄條目。讀取完成後,將返回一個Promise,將使用fs.Dirent進行解析;如果沒有更多的目錄讀取,則返回null。

範例1:

// Node.js program to demonstrate the    
// fsPromises.opendir() Method 
  
// Importing File System module 
const fs = require('fs') 
  
fs.promises.opendir('./test1') 
    .then(dir => { 
        console.log('Directory is opened') 
  
        // Path to the directory 
        console.log( 
        `Path to the directory:${dir.path}`) 
  
        // Closing directory 
        return dir.close() 
    }) 
  
    .then(() => { 
        console.log('Directory closed') 
  
        console.log('\nFurther attempt to'
            + ' read sub-directories\n') 
  
        // Further attemp to access the  
        // directory results in error 
        return dir.read() 
    }) 
  
    .then(dirent => { 
  
        // Does not execute since directory 
        // is closed catch block runs instead 
        console.log(dirent) 
    }) 
    .catch(err => { 
        console.log('Error, Something went wrong!') 
    })

使用async-await實現相同的函數

// Node.js program to demonstrate the    
// fsPromises.opendir() Method 
  
// Importing File System module 
const fs = require('fs') 
  
const readDir = async (path) => { 
  
    // Opeaning directory 
    const dir = await fs.promises.opendir(path) 
    console.log('Directory is opened') 
  
    // Path to the directory 
    console.log(`Path to the directory:${dir.path}`) 
  
    // Closing directory 
    await dir.close() 
    console.log('Directory closed') 
  
    console.log('\nFurther attempt '
            + 'to read sub-directories\n') 
  
    // Further attemp to access the directory 
    // results in error does not execute 
    // since directory is closed catch 
    // block runs instead 
    const subDir = await dir.read() 
    console.log(subDir) 
} 
  
readDir('./test1') 
    .catch(err => { 
        console.log('Error, Something went wrong!') 
    })

輸出:

  Directory is opened
  Path to the directory:test1
  Directory closed

  Further attempt to read sub-directories

  Error, Something went wrong!

範例2:

// Node.js program to demonstrate the    
// fsPromises.opendir() Method 
  
// Importing File System module 
const fs = require('fs') 
  
fs.promises.opendir('./test1') 
    .then(dir => { 
        console.log('Directory is opened') 
  
        // Path to the directory 
        console.log(`Path to the directory:${dir.path}`) 
  
        // Reading sub-directories or files 
  
        console.log('\nReading sub-directories:\n') 
        return dir.read() 
    }) 
  
    .then(dirent => { 
        console.log(`Sub-Directory:${dirent.name}`) 
  
        // Reading further sub directories 
        return dir.read() 
    }) 
  
    .then(dirent => { 
        console.log(`Sub-Directory:${dirent.name}`) 
        return dir.read() 
    }) 
  
    .then(dirent => { 
        console.log(`Sub-Directory:${dirent.name}`) 
        return dir.read() 
    }) 
    .then(dirent => { 
        console.log(`Sub-Directory:${dirent.name}`) 
        return dir.read() 
    }) 
    .then(dirent => { 
        console.log(`Sub-Directory:${dirent.name}`) 
        return dir.read() 
    }) 
    .catch(err => { 
        console.log('Error, Something went wrong!') 
    })

使用async-await實現相同的函數

// Node.js program to demonstrate the    
// fsPromises.opendir() Method 
  
// Importing File System module 
const fs = require('fs') 
  
const readDir = async (path) => { 
  
    // Opeaning directory 
    const dir = await fs.promises.opendir(path) 
    console.log('Directory is opened') 
  
    // Path to the directory 
    console.log(`Path to the directory:${dir.path}`) 
  
    // Reading sub-directories or files 
    const subDir1 = await dir.read() 
    const subDir2 = await dir.read() 
    const subDir3 = await dir.read() 
    const subDir4 = await dir.read() 
    const subDir5 = await dir.read() 
  
    // Printing 
    console.log(`Sub-Directory:${subDir1.name}`) 
    console.log(`Sub-Directory:${subDir2.name}`) 
    console.log(`Sub-Directory:${subDir3.name}`) 
    console.log(`Sub-Directory:${subDir4.name}`) 
    console.log(`Sub-Directory:${subDir5.name}`) 
} 
  
readDir('./test1') 
    .catch(err => { 
        console.log('Error, Something went wrong!') 
    })

輸出:

  Directory is opened
  Path to the directory:test1

  Reading sub-directories:

  Sub-Directory:example1.txt
  Sub-Directory:example2.txt
  Sub-Directory:example3.txt
  Sub-Directory:example4.txt
  Sub-Directory:null

參考: https://nodejs.org/dist/latest-v14.x/docs/api/fs.html#fs_fspromises_opendir_path_options




相關用法


注:本文由純淨天空篩選整理自hunter__js大神的英文原創作品 Node.js | fsPromises.opendir() Method。非經特殊聲明,原始代碼版權歸原作者所有,本譯文未經允許或授權,請勿轉載或複製。