📜  Node.js fs.truncateSync() 方法

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

Node.js fs.truncateSync() 方法

fs.truncateSync() 方法用于同步更改文件的大小,即增加或减小文件大小。它将路径中文件的长度更改 len 个字节。如果 len 短于文件的当前长度,则文件将被截断为该长度。如果它大于文件长度,则通过附加空字节 (x00) 对其进行填充,直到达到 len。

句法:

fs.truncateSync( path, len )

参数:此方法接受上面提到的两个参数,如下所述:

  • path:它是一个字符串,缓冲区,URL,表示必须截断的文件的路径。
  • len:它是一个整数,它指定文件将被截断的文件长度。它是一个可选参数。默认值为 0,这意味着将截断整个文件。

下面的示例说明了 Node.js 中的fs.truncateSync() 方法

示例 1:

// Node.js program to demonstrate the
// fs.truncateSync() method
  
// Import the filesystem module
const fs = require('fs');
  
console.log("Contents of file before truncate:")
console.log(fs.readFileSync('example_file.txt', 'utf8'));
  
fs.truncateSync('example_file.txt', 18);
  
console.log("Contents of file after truncate:")
console.log(fs.readFileSync('example_file.txt', 'utf8'));

输出:

Contents of file before truncate:
This is an example file for the truncateSync() method.
Contents of file after truncate:
This is an example

示例 2:

// Node.js program to demonstrate the
// fs.truncateSync() method
  
// Import the filesystem module
const fs = require('fs');
  
console.log("Contents of file before truncate:")
console.log(fs.readFileSync('example_file.txt', 'utf8'));
  
// Truncate the whole file
fs.truncateSync('example_file.txt');
  
console.log("Contents of file after truncate:")
console.log(fs.readFileSync('example_file.txt', 'utf8'));

输出:

Contents of file before truncate:
This is an example file for the truncateSync() method.
Contents of file after truncate:

参考: https://nodejs.org/api/fs.html#fs_fs_truncatesync_path_len