Node.js fs.close() Method
The fs.close() method is used to asynchronously close the given file descriptor thereby clearing the file that is associated with it. This will allow the file descriptor to be reused for other files. Calling fs.close() on a file descriptor while some other operation is being performed on it may lead to undefined behavior.
Syntax:
fs.close( fd, callback )
Parameters: This method accepts two parameters as mentioned above and described below:
- fd: It is an integer that denotes the file descriptor of the file for which to be closed.
- callback: It is a function that would be called when the method is executed.
- err: It is an error that would be thrown if the method fails.
Below examples illustrate the fs.close() method in Node.js:
Example 1: This example shows the closing of a file descriptor.
const fs = require( 'fs' );
file_descriptor = fs.openSync( "example.txt" );
console.log( "The file descriptor is:" , file_descriptor);
fs.close(file_descriptor, (err) => {
if (err)
console.error( 'Failed to close file' , err);
else {
console.log( "\n> File Closed successfully" );
}
});
|
Output:
The file descriptor is: 3
> File Closed successfully
Example 2: This example shows the closing of a file descriptor and trying to access that closed file descriptor again.
const fs = require( 'fs' );
file_descriptor = fs.openSync( "example.txt" );
console.log( "The file descriptor is:" , file_descriptor);
console.log( "\n> Finding the stats of the file" );
try {
statsObj = fs.fstatSync(file_descriptor);
console.log( "Stats of the file generated" );
console.log( "\n> Closing the file descriptor" );
fs.close(file_descriptor, (err) => {
if (err)
console.error( "Failed to close file" , err);
else {
console.log( "File Closed successfully" );
try {
console.log( "\n> Finding the stats of the file again" );
statsObj = fs.fstatSync(file_descriptor);
console.log( "Stats of the file generated" );
}
catch (err) {
console.error( "Cannot find stats of file" , err);
}
}
});
} catch (err) {
console.error( "Cannot find stats of file" , err);
}
|
Output:
The file descriptor is: 3
> Finding the stats of the file
Stats of the file generated
> Closing the file descriptor
File Closed successfully
> Finding the stats of the file again
Cannot find stats of file Error: EBADF: bad file descriptor, fstat
at Object.fstatSync (fs.js:897:3)
at G:\tutorials\nodejs-fs-close\index.js:42:23
at FSReqCallback.oncomplete (fs.js:146:23) {
fd: 3,
errno: -4083,
syscall: 'fstat',
code: 'EBADF'
}
Reference: https://nodejs.org/api/fs.html#fs_fs_close_fd_callback
Last Updated :
08 Oct, 2021
Like Article
Save Article
Share your thoughts in the comments
Please Login to comment...