node.js - 使用 express.js 下载文件的缓冲区
问题描述
您好,下面的 javascript 代码允许我从文件系统中恢复文件并将它们发送到前端,但是,当我运行代码时,出现以下错误是什么原因造成的?
错误: TypeError [ERR_INVALID_ARG_TYPE]:第一个参数必须是 string、Buffer、ArrayBuffer、Array 或 Array-like Object 类型之一。收到的类型对象,在此代码上
JavaScript 代码:
http.createServer(function(req, res) {
console.log("Recupero immagini");
var request = url.parse(req.url, true);
var action = request.pathname;
//Recupero il logo della società
if (action == '/logo.jpg') {
console.log("Recupero logo");
var img = fs.readFileSync('./Controller/logo.jpg');
res.writeHead(200, {
'Content-Type': 'image/jpeg'
});
res.end(img, 'binary');
}
//Recupero la firma del tecnico
else if (action == '/firmatecnico.png') {
console.log("Recupero logo tecnico");
var img2 = fs.readFileSync('./firmatecnico.png');
res.writeHead(200, {
'Content-Type': 'image/png'
});
res.end(img2, 'binary');
}
}).listen(8570);
解决方案
虽然我不确定错误的原因是什么,但您可以尝试从文件中创建一个读取流,并将它们通过管道传输到响应对象中(这是有利的,因为它不会将整个文件读入内存):
const http = require('http');
const fs = require('fs');
http.createServer(function(req, res) {
// ...
const fileStream = fs.createReadStream('./path/to/your/file');
fileStream.pipe(res);
// ...
}).listen(8570);
推荐阅读
- javascript - Puppeteer.js - 删除 Chrome 背景信息
- dynamics-crm - 表单显示空白字段而不是 DB 数据值
- r - 删除每组数据帧中的异常值
- node.js - 如何避免 DEADLINE_EXCEEDED 解析 firestore 数据库发送推送通知?
- python - 是否可以通过文本获取元素并使用 bs4 将其删除?
- wix - 可以关闭安装程序的控件
- python - 当 Celery Beat 发送一个到期任务时,为什么 MainProcess 收到了三个不同的任务?
- arrays - 带有二维数组的分段错误 shmat()
- delphi-7 - 快报4 Property DataOnly 不存在?
- python - 在破折号/情节中更改语言