riki
riki

Reputation: 1725

Buffer for downloading files with express.js

Hello the javascript code below allows me to recover the files from the file system and send them to the frontend, however, when I run the code I have the following error what is it due to?

Error: TypeError [ERR_INVALID_ARG_TYPE]: The first argument must be one of type string, Buffer, ArrayBuffer, Array, or Array-like Object. Received type object, on this code

JavaScript Code:

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

Upvotes: 1

Views: 699

Answers (1)

eol
eol

Reputation: 24565

Although I'm not sure what the cause for the error is, you can try creating a read-stream from the files an pipe them into the response object (this is favorable as it does not read the whole file into memory):

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

Upvotes: 1

Related Questions