Skip to content

Commit ac82261

Browse files
Masashi Hiranovsemozhetbyt
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 6caecc6 commit ac82261

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
@@ -3572,8 +3572,16 @@ console.log(fs.readFileSync('temp.txt', 'utf8'));
35723572
// Prints: Node.js
35733573

35743574
async function doTruncate() {
3575-
const fd = await fsPromises.open('temp.txt', 'r+');
3576-
await fsPromises.ftruncate(fd, 4);
3575+
let filehandle = null;
3576+
try {
3577+
filehandle = await fsPromises.open('temp.txt', 'r+');
3578+
await filehandle.truncate(4);
3579+
} finally {
3580+
if (filehandle) {
3581+
// close the file if it is opened.
3582+
await filehandle.close();
3583+
}
3584+
}
35773585
console.log(fs.readFileSync('temp.txt', 'utf8')); // Prints: Node
35783586
}
35793587

@@ -3591,8 +3599,16 @@ console.log(fs.readFileSync('temp.txt', 'utf8'));
35913599
// Prints: Node.js
35923600

35933601
async function doTruncate() {
3594-
const fd = await fsPromises.open('temp.txt', 'r+');
3595-
await fsPromises.ftruncate(fd, 10);
3602+
let filehandle = null;
3603+
try {
3604+
filehandle = await fsPromises.open('temp.txt', 'r+');
3605+
await filehandle.truncate(10);
3606+
} finally {
3607+
if (filehandle) {
3608+
// close the file if it is opened.
3609+
await filehandle.close();
3610+
}
3611+
}
35963612
console.log(fs.readFileSync('temp.txt', 'utf8')); // Prints Node.js\0\0\0
35973613
}
35983614

0 commit comments

Comments
 (0)