user2290820
user2290820

Reputation: 2759

Reuse the write stream without ending it and declaring new stream over and over again

this function is inside another function which sets the wStream write stream to a file where the wStream runs once successfully.

running this however

fs.watch(fname, function watcher (evt, fname) {


        if (evt === 'change') {
            wStream.write("File " + fname + " changed\n");

        } else if (evt === 'rename') {
            wStream.write("File " + orig + " renamed\n");

        }

yields this error

events.js:85
      throw er; // Unhandled 'error' event
            ^
Error: write after end
    at writeAfterEnd (_stream_writable.js:167:12)
    at WriteStream.Writable.write (_stream_writable.js:214:5)

How can I keep reusing it without ending this stream?

UPDATE As pointed out in the comments section, there is a process ending this stream explicitly.

I am running a child_process.spawn method on it like

SomeSpawn.stdout.pipe( wStream ); 

Why and how is it responsible for closing this stream? And how can I stop it from closing it explicitly? something like {end:false}?

Upvotes: 3

Views: 1920

Answers (1)

Rodrigo Medeiros
Rodrigo Medeiros

Reputation: 7862

child_process.spawn returns a ChildProcess object. This process has its own stdout, which it's a ReadableStream. A ReadableStream, when piped to a writable stream, calls end() on this writable stream when it finishes reading.

If you don't want to let the readable stream close the destination stream automatically in the end, just pass to pipe the option { end: false }, like:

SomeSpawn.stdout.pipe( wStream, { end: false } ); 

In this case, you'll have to close it manually sometime in the future.

Upvotes: 6

Related Questions