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:

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