如何在 Node.js 中使用 Promise 操作基于回调的 fs.rename() 方法?
fs.rename()方法在 Node.js 的文件系统模块中定义。文件系统模块基本上是与用户计算机的硬盘交互。 rename() 方法用于将给定旧路径处的文件重命名为给定的新路径。如果新路径文件已经存在,则会被覆盖,如果新路径存在目录,则会发生错误。
fs.rename() 方法基于回调。使用回调方法导致回调嵌套或回调地狱问题的可能性很大。因此,为了避免这种情况,我们几乎总是喜欢使用基于 Promise 的方法。使用一些额外的 node.js 方法,我们可以以 promise 的方式操作基于回调的方法。
句法:
fs.rename(oldPath, newPath)
注意:如果我们使用 Promise 操作方法,则不需要回调。
参数:此方法接受上面提到的两个参数,如下所述:
- oldpath:它是一个字符串、缓冲区或 URL,用于指定必须重命名的文件的路径。
- newpath:它是一个字符串、缓冲区或 URL,用于指定要替换旧文件的文件的路径。
方法:基于回调的 fs.rename() 方法。要使用 Promise 操作它,首先,我们使用实用程序模块中定义的 promisify() 方法将其转换为基于 Promise 的方法。
示例 1:文件名:index.js
// Importing File System and Utilities module
const fs = require('fs')
const util = require('util')
// Convert callback based methods to promise
// based methods
const readDir = util.promisify(fs.readdir)
const rename = util.promisify(fs.rename)
readDir(process.cwd())
.then(files => {
console.log(`Contents before rename operation: `)
// Contents of the current directory
for(let file of files) {
console.log(file)
}
console.log('\nAttempt to rename file : \n')
// Rename operation
return rename('test.txt', 'testFile.txt')
})
.then(() => {
// The process.cwd() gives current working
// directory
return readDir(process.cwd())
})
.then(files => {
console.log(`Contents after rename operation: `)
// Contents of the current directory
for(let file of files) {
console.log(file)
}
})
.catch(err => {
console.log(`Error occurs,
Error code -> ${err.code},
Error No -> ${err.errno}`);
})
使用 async-await 实现相同的功能。
// Importing File System and Utilities module
const fs = require('fs')
const util = require('util')
// Convert callback based methods to promise
// based methods
const readDir = util.promisify(fs.readdir)
const rename = util.promisify(fs.rename)
const renameOperation = async (oldpath, newpath) => {
console.log(`Contents before rename operation: `)
// Fetching contents of the directory before
// rename operation. The process.cwd() gives
// current working directory
const oldFiles = await
fs.promises.readdir(process.cwd())
// Contents of the current working directory
for(let file of oldFiles){
console.log(file)
}
console.log('\nAttempt to rename file : \n')
// Rename operation
await fs.promises.rename(oldpath, newpath)
console.log(`Contents after rename operation: `)
// Fetching contents of directory before
// rename operation
const newFiles = await
fs.promises.readdir(process.cwd())
// Contents of the current working directory
for(let file of newFiles) {
console.log(file)
}
}
renameOperation('test.txt', 'testFile.txt')
.catch(err => {
console.log(`Error occurs, Error code -> ${err.code},
Error No -> ${err.errno}`);
});
使用以下命令运行index.js文件:
node index.js
运行程序前的目录结构:
运行程序后的目录结构:
输出:
示例 2:当给定 newpath 不是文件路径而是目录时。
文件名:index.js
// Importing File System and Utilities module
const fs = require('fs')
const util = require('util')
// Convert callback based methods to promise
// based methods
const readDir = util.promisify(fs.readdir)
const rename = util.promisify(fs.rename)
readDir(process.cwd())
.then(files => {
console.log(`Contents before rename operation: `)
// Contents of the current directory
for(let file of files) {
console.log(file)
}
console.log('\nAttempt to rename file : \n')
// Rename operation
return rename('testFile.txt', 'test')
})
.then(() => {
// The process.cwd() gives current
// working directory
return readDir(process.cwd())
})
.then(files => {
console.log(`Contents after rename operation: `)
// Contents of the current directory
for(let file of files) {
console.log(file)
}
})
.catch(err => {
console.log(`Error occurs,
Error code -> ${err.code},
Error No -> ${err.errno}`);
})
使用 async-await 实现相同的功能。
// Importing File System and Utilities module
const fs = require('fs')
const util = require('util')
// Convert callback based methods to promise
// based methods
const readDir = util.promisify(fs.readdir)
const rename = util.promisify(fs.rename)
const renameOperation = async (oldpath, newpath) => {
console.log(`Contents before rename operation: `)
// Fetching contents of directory before
// rename operation. The process.cwd()
// gives current working directory
const oldFiles = await readDir(process.cwd())
// Contents of the current working directory
for(let file of oldFiles) {
console.log(file)
}
console.log('\nAttempt to rename file : \n')
// Rename operation
await rename(oldpath, newpath)
console.log(`Contents after rename operation: `)
// Fetching contents of directory before rename operation
const newFiles = await readDir(process.cwd())
// Contents of the current working directory
for(let file of newFiles) {
console.log(file)
}
}
renameOperation('testFile.txt', 'test')
.catch(err => {
console.log(`Error occurs,
Error code -> ${err.code},
Error No -> ${err.errno}`);
});
使用以下命令运行index.js文件:
node index.js
输出: