67

I can't find more about fs.close explain in nodejs API. I want to know what the scenario call fs.close is necessary. for example:

var fs =  require('fs');
fs.writeFile("/home/a.tex","abc"); or like fs.appendFile("/home/a.tex","close")
fs.close(); //is it necessary?

Are there any effects if i don't call fs.close?

Any help is appreciated.

Daniel Flippance
  • 6,673
  • 3
  • 39
  • 53
L.T
  • 2,287
  • 2
  • 17
  • 28

1 Answers1

105

You don't need to use fs.close after fs.readFile, fs.writeFile, or fs.appendFile as they don't return a fd (file descriptor). Those open the file, operate on it, and then close it for you.

The streams returned by fs.createReadStream and fs.createWriteStream close after the stream ends but may be closed early. If you have paused a stream, you must call close on the stream to close the fd or resume the stream and let it end after emitting all its data.

But if you call fs.open or any of the others that give a fd, you must eventually fs.close the fd that you are given.

Dan D.
  • 67,516
  • 13
  • 93
  • 109
  • 2
    May you describe the penalties that occur when you fail to call `close()`, why garbage collection doesn’t take care of this for you, and what type of programs/code/patterns would actually encounter issues when forgetting to call `fs.close()`? – binki Oct 24 '16 at 14:23
  • What happens if `fd` goes out of scope? Will it close automatically or not? – mpen Oct 24 '16 at 18:53
  • 9
    @binki failing to close a file descriptor won't immediately cause issues, but there is a limit on how many file descriptors can be open at a time. So if you repeatedly open and fail to close file descriptors you will eventually get hit with an `EMFILE: too many open files` error. – idbehold Dec 06 '16 at 15:16
  • 2
    @mpen the file descriptor will remain open even if it goes out of scope. It will not automatically close. – idbehold Dec 06 '16 at 15:17
  • 2
    What if the main NodeJS process from which the `fs.open` was called is terminated? Then does the OS consider the file handle still reserved? – Steverino Dec 29 '16 at 07:14
  • You can call `fs.readFile`, `fs.writeFile`, and `fs.appendFile` with the first argument of a file descriptor (number). If you do, you should also call `fs.close` when you are done reading/writing/appending. – David Dooling Apr 19 '19 at 17:26
  • 1
    @Steverino, once a process exits, its resources will be released. In other words, the file handle will no longer be "reserved". – David Dooling Apr 19 '19 at 17:29