fs.truncateSync()方法用於同步更改文件大小,即增加或減小文件大小。它將路徑上的文件長度更改為len個字節。如果len短於文件的當前長度,則文件將被截斷為該長度。如果它大於文件長度,則通過附加空字節(x00)來填充它,直到達到len。
用法:
fs.truncateSync( path, len )
參數:該方法接受上述和以下所述的兩個參數:
- path:這是一個字符串,Buffer,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
相關用法
- Node.js GM resize()用法及代碼示例
- Node.js GM sharpen()用法及代碼示例
- Node.js GM quality()用法及代碼示例
- Node.js GM raise()用法及代碼示例
- Node.js GM whiteThreshold()用法及代碼示例
- Node.js GM thumbnail()用法及代碼示例
- Node.js GM threshold()用法及代碼示例
- Node.js GM transparent()用法及代碼示例
- Node.js GM whitePoint()用法及代碼示例
- Node.js GM drawPolyline()用法及代碼示例
注:本文由純淨天空篩選整理自sayantanm19大神的英文原創作品 Node.js | fs.truncateSync() Method。非經特殊聲明,原始代碼版權歸原作者所有,本譯文未經允許或授權,請勿轉載或複製。