express.js 下载文件的缓冲区

Buffer for downloading files with express.js

你好下面的 javascript 代码允许我从文件系统恢复文件并将它们发送到前端,但是,当我 运行 代码时我有以下错误这是什么由于?

错误:类型错误[ERR_INVALID_ARG_TYPE]:第一个参数必须是字符串、缓冲区、数组缓冲区、数组或类数组对象之一。接收类型对象,在此代码

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);