What is destroy?
The 'destroy' npm package is used to destroy a stream, such as a request or response, ensuring that it cannot be used anymore. It is particularly useful for ensuring that file descriptors are closed and memory usage is cleaned up after streams are no longer needed.
What are destroy's main functionalities?
Destroy a stream
This code sample demonstrates how to destroy a readable stream using the 'destroy' package. Once the stream is destroyed, it cannot emit any more events or be used to read data.
const destroy = require('destroy');
const fs = require('fs');
const stream = fs.createReadStream('file.txt');
stream.on('data', (chunk) => {
console.log(chunk);
});
// Destroy the stream
destroy(stream);
Other packages similar to destroy
pump
The 'pump' package is similar to 'destroy' in that it helps manage stream lifecycle. It pipes streams together and destroys all of them if one of them closes. Compared to 'destroy', 'pump' is more about connecting streams and handling their collective destruction.
end-of-stream
The 'end-of-stream' package is used to call a callback when a stream has finished or failed, which is somewhat similar to 'destroy' in managing stream end lifecycle. Unlike 'destroy', it does not destroy the stream but rather provides a way to detect the end of a stream.
through2
The 'through2' package is a tiny wrapper around Node.js streams.Transform, making it easier to create transform streams. While it does not directly destroy streams like 'destroy', it can be used to manage stream transformations and can be combined with stream destruction for cleanup purposes.
Destroy
Destroy a stream.
This module is meant to ensure a stream gets destroyed, handling different APIs
and Node.js bugs.
API
var destroy = require('destroy')
destroy(stream)
Destroy the given stream. In most cases, this is identical to a simple
stream.destroy()
call. The rules are as follows for a given stream:
- If the
stream
is an instance of ReadStream
, then call stream.destroy()
and add a listener to the open
event to call stream.close()
if it is
fired. This is for a Node.js bug that will leak a file descriptor if
.destroy()
is called before open
. - If the
stream
is not an instance of Stream
, then nothing happens. - If the
stream
has a .destroy()
method, then call it.
The function returns the stream
passed in as the argument.
Example
var destroy = require('destroy')
var fs = require('fs')
var stream = fs.createReadStream('package.json')
destroy(stream)