Node.js fs.ftruncateSync() 方法
fs.ftruncateSync() 方法用于同步更改文件的大小,即增加或减小文件大小。它将路径中文件的长度更改 len 个字节。如果 len 短于文件的当前长度,则文件将被截断为该长度。如果它大于文件长度,则通过附加空字节 (x00) 对其进行填充,直到达到 len。它类似于 truncateSync() 方法,不同之处在于它接受要截断的文件的文件描述符。
句法:
fs.ftruncateSync( fd, len )
参数:此方法接受上面提到的两个参数,如下所述:
- fd:它是一个整数值,表示要截断的文件的文件描述符。
- len:它是一个整数值,它指定文件将被截断的文件长度。它是一个可选参数。默认值为 0,这意味着将截断整个文件。
下面的示例说明了 Node.js 中的fs.ftruncateSync() 方法:
示例 1:
// Node.js program to demonstrate the
// fs.ftruncateSync() method
// Import the filesystem module
const fs = require('fs');
console.log("Contents of file before truncate:")
console.log(fs.readFileSync('example_file.txt', 'utf8'));
// Get the file descriptor of the file
const fd = fs.openSync('example_file.txt', 'r+');
// Truncate the whole file
fs.ftruncateSync(fd);
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 ftruncateSync() method.
Contents of file after truncate:
示例 2:
// Node.js program to demonstrate the
// fs.ftruncateSync() method
// Import the filesystem module
const fs = require('fs');
console.log("Contents of file before truncate:")
console.log(fs.readFileSync('example_file.txt', 'utf8'));
// Get the file descriptor of the file
const fd = fs.openSync('example_file.txt', 'r+');
// Decrease the file size
fs.ftruncateSync(fd, 18);
console.log("Contents of file after truncate:")
console.log(fs.readFileSync('example_file.txt', 'utf8'));
// Increase the file size
fs.ftruncateSync(fd, 25);
console.log("Contents of file in bytes after truncate:")
console.log(fs.readFileSync('example_file.txt'));
输出:
Contents of file before truncate:
This is an example file for the ftruncateSync() method.
Contents of file after truncate:
This is an example
Contents of file in bytes after truncate:
参考: https://nodejs.org/api/fs.html#fs_fs_ftruncatesync_fd_len