Skip to content

Commit 1f3eb1c

Browse files
Masashi Hiranotargos
Masashi Hirano
authored andcommitted
doc: fix filehandle.truncate() sample codes
PR-URL: #20913 Reviewed-By: James M Snell <jasnell@gmail.com> Reviewed-By: Benjamin Gruenbaum <benjamingr@gmail.com> Reviewed-By: Vse Mozhet Byt <vsemozhetbyt@gmail.com> Reviewed-By: Ruben Bridgewater <ruben@bridgewater.de> Reviewed-By: Rich Trott <rtrott@gmail.com>
1 parent b242248 commit 1f3eb1c

File tree

1 file changed

+20
-4
lines changed

1 file changed

+20
-4
lines changed

doc/api/fs.md

Lines changed: 20 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -3562,8 +3562,16 @@ console.log(fs.readFileSync('temp.txt', 'utf8'));
35623562
// Prints: Node.js
35633563

35643564
async function doTruncate() {
3565-
const fd = await fsPromises.open('temp.txt', 'r+');
3566-
await fsPromises.ftruncate(fd, 4);
3565+
let filehandle = null;
3566+
try {
3567+
filehandle = await fsPromises.open('temp.txt', 'r+');
3568+
await filehandle.truncate(4);
3569+
} finally {
3570+
if (filehandle) {
3571+
// close the file if it is opened.
3572+
await filehandle.close();
3573+
}
3574+
}
35673575
console.log(fs.readFileSync('temp.txt', 'utf8')); // Prints: Node
35683576
}
35693577

@@ -3581,8 +3589,16 @@ console.log(fs.readFileSync('temp.txt', 'utf8'));
35813589
// Prints: Node.js
35823590

35833591
async function doTruncate() {
3584-
const fd = await fsPromises.open('temp.txt', 'r+');
3585-
await fsPromises.ftruncate(fd, 10);
3592+
let filehandle = null;
3593+
try {
3594+
filehandle = await fsPromises.open('temp.txt', 'r+');
3595+
await filehandle.truncate(10);
3596+
} finally {
3597+
if (filehandle) {
3598+
// close the file if it is opened.
3599+
await filehandle.close();
3600+
}
3601+
}
35863602
console.log(fs.readFileSync('temp.txt', 'utf8')); // Prints Node.js\0\0\0
35873603
}
35883604

0 commit comments

Comments
 (0)