Skip to content

Prevent [ERR_STREAM_PREMATURE_CLOSE] error log when intentionally closing a stream before end #52853

Open
@spinlud

Description

@spinlud

Version

18.18.0

Platform

Darwin arm64

Subsystem

node:internal/streams

What steps will reproduce the bug?

I have a call to a database which returns a stream. When consuming the stream, I need to end it prematurely if a certain condition is met:

import {pipeline} from 'stream/promises';
import {createWriteStream} from 'fs';

async function* myAsyncGenerator() {
	const stream = await someCalltoDb();

	for await (const rows of stream) {
		for (const row of rows) {
			// Stop consuming the stream if a certain condition is true
			if (someConditionIsTrue) {
				return stream.destroy();
			}

			yield row;
		}
	}
}

(async () => {
	const asyncGen = myAsyncGenerator();
	const outputStream = createWriteStream('output.txt');
	await pipeline(asyncGen, outputStream);
})();

This code terminates successfully (exit code 0) but it logs the following[ERR_STREAM_PREMATURE_CLOSE] error on the console:

image

How often does it reproduce? Is there a required condition?

No response

What is the expected behavior? Why is that the expected behavior?

I could be wrong, but this [ERR_STREAM_PREMATURE_CLOSE] error doesn't seem to originate on the stream object received from the call to the database, I suspect instead that this can orginate from another stream that is writing on this one (e.g. a stream from the socket who is writing the data?).

In this case I am voluntarily closing the stream before consuming all the data, so I don't want to see this [ERR_STREAM_PREMATURE_CLOSE] logged on the console. Also it doesn't seem to be an error, but just the log of an error, because the program terminates with success (exit code 0).

Is there any way to prevent this [ERR_STREAM_PREMATURE_CLOSE] error log to appear in the console?

What do you see instead?

Error [ERR_STREAM_PREMATURE_CLOSE]: Premature close
    at new NodeError (node:internal/errors:405:5)
    at Transform.onclose (node:internal/streams/end-of-stream:159:30)
    at Transform.emit (node:events:529:35)
    at Transform.emit (node:domain:489:12)
    at emitCloseNT (node:internal/streams/destroy:132:10)
    at processTicksAndRejections (node:internal/process/task_queues:81:21) {
  code: 'ERR_STREAM_PREMATURE_CLOSE'
}

Process finished with exit code 0

Additional information

No response

Metadata

Metadata

Assignees

No one assigned

    Labels

    questionIssues that look for answers.streamIssues and PRs related to the stream subsystem.

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions