How to create an endpoint that downloads a local file as soon as requested in Nodejs?

Asked

Viewed 14 times

-1

I have a file in my project that I need to make available for download, through an endpoint that when requested will automatically download, but I can not use any framework, only Nodejs.

1 answer

0


If you are not using Express, to download a local file you can do so:

const http = require("http");
const port = process.env.PORT || 5000;
const fs = require('fs');

http
  .createServer((req, response) => {

    // Rotas
    const url = req.url;
    if (url === "/download") {
        const filePath = "/caminho/do/arquivo.zip";
        const fileName = "nome_do_arquivo.zip";

        // Verificar se o arquivo existe no caminho informado
        fs.stat(filePath, function (err, stats) {
            if (err) {
                response.writeHead(400, { "Content-Type": "text/plain" });
                response.end("ERROR File does not exist");
            } else {
                response.writeHead(200, {
                    "Content-Type": "application/octet-stream",
                    "Content-Disposition": "attachment; filename=" + fileName
                });
                fs.createReadStream(filePath).pipe(response);
                
            }
            
        });
    }
    
  })
  .listen(port, () => {
    console.log(`Server listening on port ${port}...`);
  });

In the above example, it was using the filesystem to check if the file exists, in positive case, the response header is changed (content-type and content-disposition). The example file extension was zip, but it could be any other extension.

const fs = require('fs');

(....)

fs.stat(filePath, function (err, stats) {
    if (err) {
        //Arquivo nao localizado
    } else {
        //Arquivo localizado, alterar o header da requisição e fazer download.
    }
    
});

If you are using the Express, it would be easier, would be like this:

app.get('/download', function(req, res){
  const file = `${__dirname}/caminho/do/arquivo.zip`;
  res.download(file); 
});

Browser other questions tagged

You are not signed in. Login or sign up in order to post.