📜  Node.js 文件句柄.truncate() 方法

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

Node.js 文件句柄.truncate() 方法

filehandle.truncate()方法在 Node.js 的文件系统模块中定义。文件系统模块基本上是与用户计算机的硬盘进行交互的。 truncate() 方法用于将文件的内部内容修改 'len' 字节。如果 len 比文件的当前长度短,则文件被截断为 len 的长度,如果大于文件长度,则通过附加空字节 (x00) 来填充,直到达到 len。

句法:

filehandle.truncate( len );

参数:此方法接受如上所述的单个参数,如下所述:

  • len:它是一个数值,指定要截断的文件的长度。它是一个可选参数,默认值为 0,即如果没有提供 len 参数,它将截断整个文件。

返回值:它返回一个promise,如果出现问题,它将在成功时不带参数地解决,或者在出现错误时以错误对象拒绝(Ex-给定路径是目录的路径或给定路径不存在)。

示例 1:此示例说明了当文件将被截断后的长度未给出时如何截断工作。

// Importing File System and 
// Utilities module
const fs = require('fs')
  
const truncateFile = async (path) => {
    let filehandle = null
  
    try {
        filehandle = await fs.promises
                .open(path, mode = 'r+')
        // Append operation
        await filehandle.truncate()
        console.log('\nTruncate done, File"
                + " contents are deleted!\n')
    } finally {
        if (filehandle) {
  
            // Close the file if it is opened.
            await filehandle.close();
        }
    }
}
  
truncateFile('./testFile.txt')
    .catch(err => {
        console.log(`Error Occurs, Error code -> 
        ${err.code}, Error NO -> ${err.errno}`)
    })

运行程序前的文件内容:

运行程序后的文件内容:

输出:

Truncate done, File contents are deleted!

示例 2:此示例说明了如何截断作品,给出了截断文件后的长度。

// Importing File System and Utilities module
const fs = require('fs')
  
// fs.readFileSync(() method reads the file
// and returns buffer form of the data 
const oldBuff = fs.readFileSync('./testFile.txt')
  
// File content after append 
const oldContent = oldBuff.toString()
console.log(`\nContents before truncate :
                         \n${oldContent}`)
  
const truncateFile = async (path, len) => {
    let filehandle = null
  
    try {
        filehandle = await fs.promises
                .open(path, mode = 'r+')
        // Append operation
        await filehandle.truncate(len)
        console.log('\nTruncate done!\n')
    } finally {
        if (filehandle) {
  
            // Close the file if it is opened.
            await filehandle.close();
        }
    }
  
    const newBuff = fs.readFileSync(path)
    //File content after truncate
    const newContent = newBuff.toString()
    console.log(`Contents after truncate :
                        \n${newContent}`)
}
  
truncateFile('./testFile.txt', 52)
    .catch(err => {
        console.log(`Error Occurs, Error code -> 
            ${err.code}, Error NO -> ${err.errno}`)
    })

输出: