📜  Node.js fs.promises.appendFile() 方法

📅  最后修改于: 2022-05-13 01:56:34.998000             🧑  作者: Mango

Node.js fs.promises.appendFile() 方法

Node.js 中 File System 模块的fs.promises.appendFile()方法用于与用户计算机的硬盘进行交互。 appendFile() 方法用于将新数据附加到现有文件中,或者如果文件不存在,则首先创建文件,然后将给定的数据附加到文件中。 fs.promises.appendFile() 方法返回一个已解决或被拒绝的承诺,从而避免了fs.appendFile()方法中可能发生的回调嵌套或回调地狱问题。

句法:

fs.promises.appendFile( path, data, options )

参数:该方法接受三个参数路径、数据和选项。选项是一个可选参数。

  • 路径:它是一个字符串、缓冲区或 URL,指定要在其中附加给定数据的目标文件的路径。
  • 数据:它是一个字符串或缓冲区,将附加到目标文件。
  • options:它是一个可选参数,以某种方式影响输出,因此我们是否将其提供给函数调用。
    • encoding:指定编码技术,默认值为'UTF8'。
    • mode:指定文件模式。文件模式允许我们创建、读取、写入或修改文件。默认值为“0o666”。
    • flag:它指定附加到文件时使用的标志。默认值为“a”。

返回值:它返回一个已解决或被拒绝的承诺。如果数据成功附加到目标文件,则承诺被解决,否则如果发生任何错误(示例指定的文件没有写入权限等),则以错误对象拒绝

示例 1:

// Importing File System module
const fs = require('fs')
  
// The readFile() method reads the file
// and returns buffer form of the data 
fs.promises.readFile('./test.txt')
    .then(buff => {
  
        // File content before append 
        const oldContent = buff.toString()
        console.log(`Before Append: ${oldContent}\n`)
  
        // Append operation
        return fs.promises.appendFile('./test.txt', 
                    '\nHey, I am newly added..!!')
    })
  
    .then(() => {
  
        // Getting new file content
        return fs.promises.readFile('./test.txt')
    })
  
    .then(buff => {
  
        // File content after append 
        const newContent = buff.toString()
        console.log(`After Append: ${newContent}\n`)
    })
  
    .catch(err => {
        console.log(err)
    })

我们可以使用 async-await 关键字实现相同的功能。

// Importing File System module
const fs = require('fs')
const appendDataToFile = async (path, data) => {
  
    // The readFile() method reads the file
    // and returns buffer form of the data 
    const oldBuffer = await fs.promises.readFile(path)
  
    // File content before append 
    const oldContent = oldBuffer.toString()
  
    // Append operation
    await fs.promises.appendFile(path, data)
  
    const newBuffer = await fs.promises.readFile(path)
  
    // File content after append 
    const newContent = newBuffer.toString()
  
    console.log(`Before Append: ${oldContent}\n`)
    console.log(`After Append: ${newContent}`)
}
  
appendDataToFile('./test.txt', 
        '\nHey, I am newly added..!!')
    .catch(err => {
        console.log(err)
    })

输出:

示例 2:当文件名的给定路径不存在时。

// Importing File System module
const fs = require('fs')
  
// Append operation
// If given file does not exist
// it will be created first then
// data is appended
fs.promises.appendFile('./test.txt', 
    'Please add me to the test file..!!')
    .then(() => {
  
        // readFile() method reads the file
        // and returns buffer form of the data 
        return fs.promises.readFile('./test.txt')
    })
  
    .then(buff => {
  
        // Appended data
        const content = buff.toString()
        console.log(`Content : ${content}`)
    })
  
    .catch(err => {
        console.log(err)
    })

使用 async-await 关键字实现相同的功能。

// Importing File System module
const fs = require('fs')
  
const appendDataToFile = async (path, data) => {
  
    // Append operation
    // If given file does not exist
    // It will created first then
    // data is appended
    await fs.promises.appendFile(path, data)
  
    // readFile() method reads the file
    // and returns buffer form of the data 
    const buff = await fs.promises.readFile(path)
  
    // File content after append 
    const content = buff.toString()
    console.log(`Content : ${content}`)
}
  
appendDataToFile('./test.txt', 
    'Please add me to the test file..!!')
    .catch(err => {
        console.log(err)
    })

运行程序前的目录结构:

运行程序后的目录结构:

输出: