VOOZH about

URL: https://www.geeksforgeeks.org/node-js/node-js-fs-close-method/

⇱ Node.js fs.close() Method - GeeksforGeeks


  • Courses
  • Tutorials
  • Interview Prep

Node.js fs.close() Method

Last Updated : 8 Oct, 2021
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. 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. 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
Comment
Article Tags:

Explore