Node.js文件下载大小异常求助:特定格式文件下载后体积变大
Node.js文件下载体积异常问题解决
你的问题核心是用UTF-8编码读取二进制文件导致的:
- 你通过
fs.readFileSync(filePath, 'utf8')把所有文件都当成UTF-8文本读取,但iso、deb、sqlite这类属于二进制文件,UTF-8编码会错误解析非文本字节,既破坏了原始数据,又因为编码转换导致文件体积异常膨胀。 - 而txt、html、jpg/png这类文件,要么本身就是UTF-8文本格式,要么二进制数据结构巧合适配UTF-8读取规则,所以下载表现正常。
修正后的代码
将文件读取逻辑改为二进制模式(直接读取Buffer,不指定编码):
const filePath = path.join(directoryPath, fileName); if (fs.existsSync(filePath)) { const fileExtension = path.extname(fileName); let fileType = mime.contentType(fileExtension); const HEADER = { 'Content-Type': fileType, 'Content-Disposition': `attachment; filename="${fileName}"` }; // 直接读取二进制Buffer,无需指定编码 const fileBuffer = fs.readFileSync(filePath); res.writeHead(200, HEADER); res.end(fileBuffer); } else { res.writeHead(404, { 'Content-Type': 'text/plain' }); res.end("File not found"); }
额外优化建议
- 大文件改用流式读取,避免占用过多内存:
// 替换readFileSync部分 const stream = fs.createReadStream(filePath); res.writeHead(200, HEADER); stream.pipe(res);
- 处理文件名中的特殊字符,避免浏览器解析异常:
'Content-Disposition': `attachment; filename="${encodeURIComponent(fileName)}"`
内容的提问来源于stack exchange,提问作者msrajwat298
相关产品推荐
相关产品推荐

