'Download PDF nodejs + expressjs

I am making a GET request to download a PDF file through the browser, but I do not get a response. I do not know where I'm going wrong. Follow my code

My Controller

download: function(req, res) {

        var nomeContrato = req.params.contrato;
        var cpfAluno = req.params.cpf

        db.query("select descricao from tparametro where valor = 'PATH'", function (err, rows) {

            if (err) {
                var message = err.message;
                console.log('Erro ' + message);

                return res.status(500).send(message);

            }else {

                var caminhoDiretorio = rows[0].descricao;
                var caminhoComSubdiretorio = caminhoDiretorio + path.sep + cpfAluno;
                var caminhoCompleto = caminhoComSubdiretorio + path.sep + nomeContrato;

                fs.readFile(caminhoCompleto, function(err, arquivo) {  
                    if (err) throw err;
                    //console.log('Arquivo:' + arquivo);
                    var data = [];
                    data.push(arquivo);
                    data = Buffer.concat(data);
                    //console.log('Arquivo:' + data);
                    res.writeHead(200, {
                        'Content-Type': 'application/pdf',
                        'Content-Disposition': 'attachment; filename=some_file.pdf',
                        'Content-Length': data.length
                      });
                      res.write(data);
                      res.end(data);
                });

            }

        });
    }

The browser receives the response

enter image description here

Response HEADER

enter image description here



Solution 1:[1]

Its easier to use 'res.sendFile(), something like :

   var filePath = "./dir/example.pdf"
   return res.sendFile(filePath);

Solution 2:[2]

Is there a reason you can't just do:

var caminhoDiretorio = rows[0].descricao;
var caminhoComSubdiretorio = caminhoDiretorio + path.sep + cpfAluno;
var caminhoCompleto = caminhoComSubdiretorio + path.sep + nomeContrato;

res.download(caminhoCompleto);

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 NiallJG
Solution 2 bendataclear