fs.ftruncate()方法用於更改文件的大小,即增加或減小文件的大小。它將路徑上的文件長度更改為len個字節。如果len短於文件的當前長度,則文件將被截斷為該長度。如果它大於文件長度,則通過附加空字節(x00)來填充它,直到達到len。它類似於truncate()方法,不同之處在於它接受要截斷的文件的文件描述符。
用法:
fs.ftruncate(fd, len, callback)
參數:此方法接受上述和以下所述的三個參數:
- fd:它是一個整數值,表示要截斷的文件的文件描述符。
- len:它是一個整數值,它指定文件的長度,之後將截斷文件。它是一個可選參數。默認值為0,這意味著整個文件將被截斷。
- callback:該方法執行時將調用該函數。
- err:如果方法失敗,將拋出此錯誤。
以下示例說明了Node.js中的fs.ftruncate()方法:
範例1:
// Node.js program to demonstrate the
// fs.ftruncate() 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+');
fs.ftruncate(fd, 24, (err) => {
if (err)
console.log(err)
else {
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 ftruncate() method. Contents of file after truncate: This is an example file
範例2:
// Node.js program to demonstrate the
// fs.ftruncate() 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.ftruncate(fd, (err) => {
if (err)
console.log(err)
else {
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 ftruncate() method. Contents of file after truncate:
參考: https://nodejs.org/api/fs.html#fs_fs_ftruncate_fd_len_callback
相關用法
- Node.js GM minify()用法及代碼示例
- Node.js GM magnify()用法及代碼示例
- Node.js GM write()用法及代碼示例
- Node.js GM drawRectangle()用法及代碼示例
- Node.js GM whitePoint()用法及代碼示例
- Node.js GM whiteThreshold()用法及代碼示例
- Node.js GM modulate()用法及代碼示例
- Node.js GM drawEllipse()用法及代碼示例
- Node.js GM drawCircle()用法及代碼示例
- Node.js GM drawPolyline()用法及代碼示例
注:本文由純淨天空篩選整理自sayantanm19大神的英文原創作品 Node.js | fs.ftruncate() Method。非經特殊聲明,原始代碼版權歸原作者所有,本譯文未經允許或授權,請勿轉載或複製。