Node.js创建Blob时报Blob is not defined错误如何解决
问题解决方案
报错原因
ReferenceError: Blob is not defined 报错是因为Blob是浏览器端提供的API,Node.js 18以下版本默认没有内置该对象。同时你当前的实现逻辑存在另一个问题:Blob是二进制对象,无法直接序列化为JSON通过接口返回,即便你在Node侧成功生成Blob,最终传给前端的也只会是空对象,无法正常使用。
解决办法
推荐方案:返回Base64编码内容,前端侧生成Blob
该方案无需额外依赖、兼容性最好,全程在内存处理无需写入本地磁盘:
后端修改后代码
saveFiles = async (res, outputJSON, testBedJson) => { const encodedOutput = btoa(JSON.stringify(outputJSON)); let preName = 'intent_based'; let fullFileName = `${preName}_${moment().format("hh_mm_ss-DD-MM-YYYY")}.ubot`; let fullFileTestBedJsonName = `test-bed_${moment().format("hh_mm_ss-DD-MM-YYYY")}.json`; const doc = new YAML.Document(); doc.contents = testBedJson; let fullFileTestBedYmlName = `test-bed_${moment().format("hh_mm_ss-DD-MM-YYYY")}.yaml`; // 替换Blob生成逻辑,返回base64编码内容和对应MIME类型 responseObj = { status: 'success', msg: 'Successfully saved the files', body: { allFiles:[ { "name": fullFileName, "type": "text/plain", "content": Buffer.from(encodedOutput).toString('base64') }, { "name": fullFileTestBedJsonName, "type": "application/json", "content": Buffer.from(JSON.stringify(testBedJson, null, 4)).toString('base64') }, { "name": fullFileTestBedYmlName, "type": "text/yaml", "content": Buffer.from(doc.toString()).toString('base64') } ] } } res.send(responseObj); }
前端配套处理代码
// 前端拿到接口返回的allFiles数组后,遍历生成Blob并触发下载 async function downloadFiles(files) { for (const file of files) { // 将base64转成Blob const binary = atob(file.content); const array = []; for (let i = 0; i < binary.length; i++) { array.push(binary.charCodeAt(i)); } const blob = new Blob([new Uint8Array(array)], { type: file.type }); // 触发浏览器下载 const url = URL.createObjectURL(blob); const a = document.createElement('a'); a.href = url; a.download = file.name; a.click(); URL.revokeObjectURL(url); } }
备选方案:Node侧直接使用Blob
如果业务要求必须在Node侧生成Blob,可选择以下两种方式:
- 升级Node.js版本到18.x及以上,该版本开始内置了Blob对象,可直接调用
- 低版本Node可安装第三方依赖
fetch-blob,导入后使用:
安装命令:npm install fetch-blob
导入代码:import Blob from 'fetch-blob'
注意:即便Node侧生成了Blob,仍然需要转成base64/ArrayBuffer后才能通过JSON接口返回给前端,无法直接传递Blob对象
内容的提问来源于stack exchange,提问作者subhra_user
相关产品推荐
相关产品推荐

