Is stream.end() synchronous?

Viewed 533

I have a class that has a maintains an instance variable called write_stream. This write_stream variable gets updated with new write streams and currently I do something like this:

const fs = require('fs');

class Test {

   constructor() {
      this.write_stream = null;
   }

   ...

   set_write_stream(new_file_path) {
      if (this.write_stream != null) {
         this.write_stream.end();
      }
      this.write_stream = fs.createWriteStream(new_file_path);
   }
}

Is this an acceptable way to do this? Is there a better way to do it? Is stream.end() synchronous, or do I need to wait for some sort of promise before continuing onto fs.createWriteStream()?

1 Answers

The nodejs docs say that writable.end() takes a callback

You can also promisify and await the callback like so:

const p = new Promise(res => this.write_stream.end(res))
await p;

Although, I don't think you should to wait for the first stream to finish before replacing it on the object. That might lead to a race condition where something tries to write to the already ended but not totally finished stream.

In other words, if something tries to .write() the stream after you call .end() it will error, so you must replace the stream right after you call .end() in order for it to be seamless.

Related