Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Download a file from NodeJS Server using hapi

I want to create a file download API using hapi. Without using res.download(), how to do it using reply()?

like image 532
Soumen Dey Avatar asked May 14 '26 08:05

Soumen Dey


2 Answers

You can also download a file from stream

const { Readable } = require('stream');

handler: async (request: any, h: Hapi.ResponseToolkit) => {
  let stream = Fs.createReadStream(filePath);
  let streamData = new Readable().wrap(stream);
  return h.response(streamData)
    .header('Content-Type', contentType)
    .header('Content-Disposition', 'attachment; filename= ' + fileName);
}

To get content type of file you can refer:

getContentType(fileExt) {
        let contentType;
        switch (fileExt) {
            case 'pdf':
                contentType = 'application/pdf';
                break;
            case 'ppt':
                contentType = 'application/vnd.ms-powerpoint';
                break;
            case 'pptx':
                contentType = 'application/vnd.openxmlformats-officedocument.preplyentationml.preplyentation';
                break;
            case 'xls':
                contentType = 'application/vnd.ms-excel';
                break;
            case 'xlsx':
                contentType = 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet';
                break;
            case 'doc':
                contentType = 'application/msword';
                break;
            case 'docx':
                contentType = 'application/vnd.openxmlformats-officedocument.wordprocessingml.document';
                break;
            case 'csv':
                contentType = 'application/octet-stream';
                break;
            case 'xml':
                contentType = 'application/xml';
                break;
        }
        return contentType;
    }
like image 200
Rahul Patil Avatar answered May 15 '26 22:05

Rahul Patil


you need to make a Buffer and then set the header and the encoding for the reply

let buf = new Buffer(xls, 'binary');

return reply(buf)
    .encoding('binary')
    .type('application/vnd.openxmlformats-officedocument.spreadsheetml.sheet')
    .header('content-disposition', `attachment; filename=test-${new Date().toISOString()}.xlsx;`);
like image 44
Thai Tran Avatar answered May 15 '26 22:05

Thai Tran



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!