Node.js如何用fetch请求content-disposition为attachment的压缩包获取内部JSON
可以实现。你当前获取到的响应是压缩包的二进制数据流,需要先对二进制流进行解压操作后才能读取到内部的JSON数据,具体实现如下:
前置代码修正
Node.js 环境不存在浏览器端的 btoa 方法,需要使用 Buffer 完成 Basic 认证的 Base64 编码,同时先把响应内容转换为二进制 Buffer 供后续解压使用:
const response = await fetch(url, { headers: { Authorization: "Basic " + Buffer.from(`${username}:${password}`).toString('base64') } }); const arrayBuffer = await response.arrayBuffer(); const buffer = Buffer.from(arrayBuffer);
分压缩格式处理
可以先通过响应头判断压缩类型,走对应处理逻辑:const contentType = response.headers.get('content-type')
1. gzip 格式(content-type: application/gzip)
直接使用 Node.js 内置的 zlib 模块解压即可,无需额外依赖:
const zlib = require('zlib/promises'); const decompressedContent = await zlib.gunzip(buffer); const jsonData = JSON.parse(decompressedContent.toString('utf8')); // 即可拿到目标JSON数据
2. zip 格式(content-type: application/zip)
zip 为多文件归档格式,需要借助第三方库处理,这里以轻量库 adm-zip 为例:
- 先安装依赖:
npm install adm-zip - 代码实现:
const AdmZip = require('adm-zip'); const zip = new AdmZip(buffer); const allFiles = zip.getEntries(); // 替换为你压缩包内实际的JSON文件名 const targetJsonFile = allFiles.find(item => item.entryName === 'target.json'); if (targetJsonFile) { const jsonStr = targetJsonFile.getData().toString('utf8'); const jsonData = JSON.parse(jsonStr); }
注意事项
- 如果压缩包设置了解压密码,需要在对应解压方法中传入密码参数,
adm-zip构造函数支持传入密码配置。 - 如果无法通过
content-type判断格式,可以解析content-disposition响应头获取文件名后缀判断。
内容的提问来源于stack exchange,提问作者jonask
相关产品推荐
相关产品推荐

