What is mimic-response?
The mimic-response npm package is designed to copy properties from one response-like object to another. This is particularly useful when you are working with streams and you want to retain the original response properties after modifying or replacing the response stream.
What are mimic-response's main functionalities?
Copying response properties
This feature allows you to copy properties from an HTTP response object to another stream. In this code sample, an HTTP GET request is made, and the response is piped through a new PassThrough stream, but before that, all properties of the original response are copied to the new stream using mimicResponse.
const http = require('http');
const mimicResponse = require('mimic-response');
http.get('http://example.com', (res) => {
const customResponse = new stream.PassThrough();
mimicResponse(res, customResponse);
res.pipe(customResponse);
});
Other packages similar to mimic-response
clone-response
The clone-response package is similar to mimic-response in that it is used to clone the response object of a Node.js HTTP response. However, clone-response creates a clone of the response stream that can be read again, while mimic-response copies the properties without creating a new readable stream.
responselike
The responselike package is designed to create an object that mimics the Node.js response object. It is similar to mimic-response but is used to create a new response-like object from scratch rather than copying properties from an existing response object.
mimic-response
Mimic a Node.js HTTP response stream
Install
$ npm install mimic-response
Usage
import {PassThrough as PassThroughStream} from 'node:stream';
import mimicResponse from 'mimic-response';
const responseStream = getHttpResponseStream();
const myStream = new PassThroughStream();
mimicResponse(responseStream, myStream);
console.log(myStream.statusCode);
API
mimicResponse(from, to)
Note #1: The from.destroy(error)
function is not proxied. You have to call it manually:
import {PassThrough as PassThroughStream} from 'node:stream';
import mimicResponse from 'mimic-response';
const responseStream = getHttpResponseStream();
const myStream = new PassThroughStream({
destroy(error, callback) {
responseStream.destroy();
callback(error);
}
});
myStream.destroy();
Please note that myStream
and responseStream
never throw. The error is passed to the request instead.
from
Type: Stream
Node.js HTTP response stream.
to
Type: Stream
Any stream.
Related