How to fix Fetch TypeError in Node.js All In One
TypeError: terminated at Fetch.onAborted (node:internal/deps/undici/undici:11000:53)
Error
undici
// ❌❌ video url https://edu.xgqfrms.xyz/dc9bb2-1733219a4a8.mp4
TypeError: terminated
at Fetch.onAborted (node:internal/deps/undici/undici:11000:53)
at Fetch.emit (node:events:513:28)
at Fetch.terminate (node:internal/deps/undici/undici:10272:14)
at Object.onError (node:internal/deps/undici/undici:11095:36)
at Request.onError (node:internal/deps/undici/undici:6477:31)
solution
use
node-fetch
instead of Node.jsundici
fetch ❓
$ npm i node-fetch
$ npm i -D @types/node-fetch
https://www.npmjs.com/package/node-fetch
import fetch from 'node-fetch';
// fetch-polyfill.js
import fetch, {
Blob,
blobFrom,
blobFromSync,
File,
fileFrom,
fileFromSync,
FormData,
Headers,
Request,
Response,
} from 'node-fetch'
if (!globalThis.fetch) {
globalThis.fetch = fetch
globalThis.Headers = Headers
globalThis.Request = Request
globalThis.Response = Response
}
// index.js
import './fetch-polyfill'
// ...
arrayBuffer
&res.clone()
import fetch from 'node-fetch';
const response = await fetch('https://example.com', {
// About 1MB
highWaterMark: 1024 * 1024
});
const result = await res.clone().arrayBuffer();
console.dir(result);
demos
async fetchVideo(url, filepath) {
const filename = `${filepath}.mp4`;
return fetch(url)
// .then((res) => res.arrayBuffer())
.then((res) => {
console.log(`loading ... ⏳`);
return res.arrayBuffer();
})
.then((buffer) => {
console.log(`finished ✅`)
let arrayBuffer = Buffer.from(buffer)
fs.writeFile(filename, arrayBuffer, (err) => {
if (err) {
console.error(err);
console.error(`❌ video url`, url);
} else {
console.log("video downloaded successfully");
}
});
})
.catch((err) => console.error(`❌❌ video url`, url, err));
/*
❌❌ video url https://edu.xgqfrms.xyz/dc9bb2-1733219a4a8.mp4
TypeError: terminated
at Fetch.onAborted (node:internal/deps/undici/undici:11000:53)
at Fetch.emit (node:events:513:28)
at Fetch.terminate (node:internal/deps/undici/undici:10272:14)
at Object.onError (node:internal/deps/undici/undici:11095:36)
at Request.onError (node:internal/deps/undici/undici:6477:31)
at errorRequest (node:internal/deps/undici/undici:8440:17)
at TLSSocket.onSocketClose (node:internal/deps/undici/undici:7895:9)
at TLSSocket.emit (node:events:525:35)
at node:net:313:12
at TCP.done (node:_tls_wrap:587:7) {
[cause]: BodyTimeoutError: Body Timeout Error
at Timeout.onParserTimeout [as _onTimeout] (node:internal/deps/undici/undici:7839:32)
at listOnTimeout (node:internal/timers:566:11)
at process.processTimers (node:internal/timers:507:7) {
code: 'UND_ERR_BODY_TIMEOUT'
}
}
*/
}