當前位置: 首頁>>編程示例 >>用法及示例精選 >>正文


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




相關用法


注:本文由純淨天空篩選整理自sayantanm19大神的英文原創作品 Node.js | fs.ftruncateSync() Method。非經特殊聲明,原始代碼版權歸原作者所有,本譯文未經允許或授權,請勿轉載或複製。