如何在 Node.js 中使用 Promise 操作基于回调的 fs.opendir() 方法?
fs.opendir()方法在 Node.js 的文件系统模块中定义。文件系统模块基本上是与用户计算机的硬盘进行交互的。用于异步打开目录的方法。
fs.opendir() 方法基于回调。使用回调方法导致回调嵌套或回调地狱问题的可能性很大。因此,为了避免这种情况,我们几乎总是喜欢使用基于 Promise 的方法。使用一些额外的 node.js 方法,我们可以以 promise 的方式操作基于回调的方法。承诺通过“fs.Dir”对象解决,该对象本身包含用于访问和关闭目录的其他功能。如果 promise 被拒绝,它将被错误对象拒绝。
句法:
fs.opendir(path, options)
注意:不需要回调,因为我们使用 Promise 操作该方法。
参数:接受上面提到的两个参数路径和选项。 options 是可选参数。
- path:它是一个 String、Buffer 或 Url,用于指定必须打开的目录的路径。
- options:它是一个可选参数,以某种方式影响输出,因此是否将其提供给函数调用。
- encoding:指定编码技术,默认为 'UTF8'
- bufferSize:它是一个数字,指定从目录读取时在内部缓冲的目录条目数。 bufferSize 的高值,可确保良好的性能,但会导致更多的内存使用。
返回:如果方法使用 Promise 操作,则返回使用“fs.Dir”对象解析的 Promise,该对象本身包含用于访问和关闭目录的其他函数。如果 promise 被拒绝,它将被错误对象拒绝。
'dir' 对象方法:
- dir.close():它异步关闭目录的资源,因此后续尝试读取将导致错误。返回一个 Promise,将在资源关闭后解决。
- dir.closeSync() :它同步关闭目录的资源,因此后续尝试读取将导致错误。
- dir.path :返回目录的路径。
- dir.read() :它异步读取下一个目录条目。读取完成后,返回一个 Promise,将使用 fs.Dirent 解析,如果没有更多目录读取,则返回 null。
方法:基于回调的 fs.opendir() 方法。要使用 Promise 操作它,首先,我们使用实用程序模块中定义的 promisify() 方法将其转换为基于 Promise 的方法。
示例 1:文件名:index.js
javascript
// Importing File System and Utilities module
const fs = require('fs')
const util = require('util')
// Convert callback based methods
// to promise based methods
const openDir = util.promisify(fs.opendir)
openDir('./testDirectory')
.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 attempt 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!')
})
javascript
// Importing File System and
// Utilities module
const fs = require('fs')
const util = require('util')
// Convert callback based methods
// to promise based methods
const openDir = util.promisify(fs.opendir)
const fetchDirectory = async (path) => {
// Opeaning directory
const dir = await 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 attempt 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)
}
fetchDirectoey('./testDirectory')
.catch(err => {
console.log('Error, Something went wrong!')
})
javascript
// Importing File System and Utilities module
const fs = require('fs')
const util = require('util')
// Convert callback based methods to
// promise based methods
const openDir = util.promisify(fs.opendir)
openDir('./testDirectory')
.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!')
})
javascript
// Importing File System and Utilities module
const fs = require('fs')
const util = require('util')
// Convert callback based methods
// to promise based methods
const openDir = util.promisify(fs.opendir)
const fetchDirectory = async (path) => {
// Opeaning directory
const dir = await openDir(path)
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')
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}`)
}
fetchDirectory('./testDirectory')
.catch(err => {
console.log('Error, Something went wrong!')
})
使用 async-await 实现相同的功能。
javascript
// Importing File System and
// Utilities module
const fs = require('fs')
const util = require('util')
// Convert callback based methods
// to promise based methods
const openDir = util.promisify(fs.opendir)
const fetchDirectory = async (path) => {
// Opeaning directory
const dir = await 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 attempt 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)
}
fetchDirectoey('./testDirectory')
.catch(err => {
console.log('Error, Something went wrong!')
})
使用以下命令运行index.js文件:
node index.js
输出:
Directory is opened
Path to the directory: testDirectory
Directory closed
Further attempt to read sub-directories:
Error, Something went wrong!
示例 2:文件名 index.js
javascript
// Importing File System and Utilities module
const fs = require('fs')
const util = require('util')
// Convert callback based methods to
// promise based methods
const openDir = util.promisify(fs.opendir)
openDir('./testDirectory')
.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 实现相同的功能。
javascript
// Importing File System and Utilities module
const fs = require('fs')
const util = require('util')
// Convert callback based methods
// to promise based methods
const openDir = util.promisify(fs.opendir)
const fetchDirectory = async (path) => {
// Opeaning directory
const dir = await openDir(path)
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')
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}`)
}
fetchDirectory('./testDirectory')
.catch(err => {
console.log('Error, Something went wrong!')
})
使用以下命令运行index.js文件:
node index.js
输出:
Directory is opened
Path to the directory: testDirectory
Reading sub-directories:
Sub-Directory : testFile1.txt
Sub-Directory : testFile2.txt
Sub-Directory : teasrFile3.txt
Sub-Directory : testFile4.txt
Sub-Directory : null