node
node copied to clipboard
Prevent [ERR_STREAM_PREMATURE_CLOSE] error log when intentionally closing a stream before end
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:
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
error doesn't seem to originate on the stream object received from the call to the database, I suspect instead that this can originate from another stream that is writing on this one (e.g. a stream from the socket who is writing the data?).
Then it looks like the database driver is not closing the socket if the stream it returned is closed or destroyed.