我正在使用node-rest-client来发出请求。
我正在用流模拟响应,但遇到一个问题,我收到此错误:
TypeError: The "stream" argument must be an instance of ReadableStream, WritableStream, or Stream. Received an instance of Socket
下面是可以运行以查看错误的简单片段。
const NodeRestClient = require('node-rest-client').Client;
const nock = require('nock');
const { Readable } = require('stream');
// Create a Readable stream from a string
const streamResponse = new Readable();
streamResponse._read = () => {};
streamResponse.push('Hello, this is a streamable buffer response');
streamResponse.push(null);
// Define the API endpoint you want to mock
const apiUrl = 'https://api.example.com';
// Use nock to intercept the HTTP request and mock the response with a stream
nock(apiUrl)
.get('/endpoint')
.reply(200, streamResponse, { 'Content-Type': 'application/octet-stream' });
// Make a request using node-rest-client
const client = new NodeRestClient();
client.get(`${apiUrl}/endpoint`, { responseType: 'arraybuffer' }, (data, response) => {
if (response.statusCode === 200) {
// Response data will be a Buffer
console.log('Mocked Streamable Buffer Response:', data.toString('utf-8'));
} else {
console.error('Error:', response.statusCode, data);
}
});
下面是堆栈跟踪:
Mocked Streamable Buffer Response: Hello, this is a streamable buffer response
node:events:495
throw er; // Unhandled 'error' event
^
<ref *2> TypeError [ERR_INVALID_ARG_TYPE]: The "stream" argument must be an instance of ReadableStream, WritableStream, or Stream. Received an instance of Socket
at new NodeError (node:internal/errors:405:5)
at eos (node:internal/streams/end-of-stream:74:11)
at IncomingMessage._destroy (node:_http_incoming:234:21)
at _destroy (node:internal/streams/destroy:109:10)
at IncomingMessage.destroy (node:internal/streams/destroy:71:5)
at endReadableNT (node:internal/streams/readable:1384:16)
at process.processTicksAndRejections (node:internal/process/task_queues:82:21)
我想了解导致此问题的原因。这个问题有解决方案/解决方法吗?
您的
knok
版本是什么?
旧版本存在一个问题,其中 knok
会自行覆盖 https.request
,从而阻止它传递逻辑来检查 node
上的流。
如果不是最新版本,请更新到最新版本并重试。 https://github.com/nock/nock/issues/2466