Electron使用fetch-node下载二进制文件解码异常(仅Win7出现)求助
Hey Alex, sorry to hear you're hitting this frustrating Windows 7-specific issue with fetch-node and large PDF downloads. Let's walk through some targeted fixes that should help resolve those periodic corrupted files (including those tiny 5KB ones):
1. Fix Stream Handling with Pipeline
The most common culprit here is incomplete stream processing, especially on older OS like Windows 7. Instead of relying on fetch-node's default response parsing, use Node.js's built-in stream.pipeline to safely write large files chunk by chunk—it handles backpressure and ensures all data is written properly.
Here's a quick implementation:
const fs = require('fs'); const { promisify } = require('util'); const pipeline = promisify(require('stream').pipeline); const fetch = require('fetch-node'); async function downloadLargePDF(url, outputPath) { const response = await fetch(url); if (!response.ok) { throw new Error(`Failed to fetch: HTTP status ${response.status}`); } // Use pipeline to handle stream safely await pipeline(response.body, fs.createWriteStream(outputPath)); }
2. Force HTTP/1.1 (Disable HTTP/2)
Windows 7 has poor support for HTTP/2, which fetch-node might be using by default. Forcing HTTP/1.1 can eliminate protocol-related glitches:
const http = require('http'); const https = require('https'); // Pick the right agent based on URL protocol const agent = url.startsWith('https') ? new https.Agent({ keepAlive: true, maxSockets: 3 }) : new http.Agent({ keepAlive: true, maxSockets: 3 }); const response = await fetch(url, { agent });
3. Add Checksum Verification & Auto-Retry
Since the issue is periodic, adding a checksum check (like SHA-256) will let you catch corrupted downloads and retry automatically. Compare the downloaded file's hash with the expected value from your server—if they don't match, re-run the download.
4. Update Fetch-Node or Switch Libraries
Fetch-node might have Windows 7-specific bugs that have been fixed in newer versions. First, try updating it with:
npm install fetch-node@latest
If that doesn't help, consider switching to more battle-tested alternatives like axios (with stream support) or even native Node.js http/https modules—they tend to have better compatibility with older operating systems.
5. Adjust Stream Buffer Size
Windows 7 has smaller default network buffer limits. Tweaking the highWaterMark option when creating your write stream can help:
fs.createWriteStream(outputPath, { highWaterMark: 64 * 1024 }); // 64KB chunks instead of default 16KB
Those tiny 5KB files you're seeing are almost certainly partial responses (just headers or a small chunk of the PDF) caused by interrupted streams. The fixes above should ensure full, consistent downloads every time on Windows 7.
内容的提问来源于stack exchange,提问作者Alex Pilugin

