Search code examples
javascriptnode.jsangulartypescriptminio

Download file from MINIO with node.js


New in node.js! please ignore incase invalid question! I am having one minio bucket hosted in local server. I wanted to download data from minio bucket to user machine with help to following flow:

Valid user on browser => Node.js backend (To validate minio access) => Minio.

Following are two concern:

  • I tried to execute my minio download commands on Node.js backend but its downloading on backend only not on user machine. How to download data on user machine?
  • Size of my download file might be very big which might not be handled by Node.js backend due to size restriction on backend. hence how to download data on user machine with small small chunk?

Any example will be really appreciated. thanks


Solution

  • To download a file at client side, you can use below headers in response:

    res.setHeader('Content-Type', 'application/octet-stream');
    res.setHeader('Content-Disposition', `attachment; filename="${fileName}"`);
    

    For chunked transfer you can use below function:

    async downloadFile(fileName: string) {
            let size = 0;
            const chunks = [];
    
            return new Promise(async (resolve, reject) => {
                try {
                    const dataStream = await MinioConfig.minioClient.getObject(this.minioConfig.bucketName, fileName);
    
                    dataStream.on('data', function (chunk) {
                        size += chunk.length;
                        chunks.push(chunk);
                    });
    
                    dataStream.on('end', function () {
                        console.log('End. Total size = ' + size);
                        const buffer = Buffer.concat(chunks, size);
                        resolve(buffer);
                    });
    
                    dataStream.on('error', function (err) {
                        console.log(err);
                        reject(err);
                    });
                } catch (error) {
                    console.log('Error downloading file:', error);
                    reject(error);
                }
            });
        }