0

I have the following code, which is a simplified example of what I am trying to do:

const fs = require('fs');

var stream = fs.createWriteStream('/tmp/file');
stream.once('open', function(fd) {
    for (var i = 0; i < 100; i += 1) {
        stream.write('' + i + "\n");
    }
    stream.end();
    stream.close();
});

I can see that fd is the file descriptor and I wanted to close it. I called fd.close(), but that is not a method.

Two questions:

  1. Should I be closing it?
  2. How do I close it?

I saw some documentation on fs.close() and fs.closeSync(). Should I use that?

Thanks.

HenryTK
  • 1,287
  • 8
  • 11
  • I thinks this [what-the-scenario-call-fs-close-is-necessary](https://stackoverflow.com/a/21177492/7967469) answers your first question and the docs answers your second question. – Ghassen Manai Jul 23 '19 at 09:42
  • The docs for [`Class: fs.WriteStream`](https://nodejs.org/api/fs.html#fs_class_fs_writestream) does not mention the `end()` or `close()` methods. – HenryTK Jul 23 '19 at 09:49
  • But `WriteStream` is a `WritableStream` ... Have a look at its docs too ... – Jonas Wilms Jul 23 '19 at 09:52
  • The [`WriteableStream` docs](https://nodejs.org/api/stream.html#stream_class_stream_writable) mentions the `end()` method, but says nothing about closing file descriptors. – HenryTK Jul 23 '19 at 09:56

1 Answers1

2

I called fd.close()

From the documentation you linked:

fd Integer file descriptor used by the WriteStream.

So fd is an integer, not an object with methods.

Should I be closing it?

Yes! Otherwise you are wasting ressources, as the stream is pending. You should end the stream, by calling .end(). That will also close the underlying file, so there is no need to manually fs.close it.

Jonas Wilms
  • 132,000
  • 20
  • 149
  • 151