I need a download service in nodejs express which can handle large files (up to 20GB) Possiblilty to pause, resume, and cancel the download within the browsers download manager.
Enter the URL in the browser:
URL: https://my-url.com/api/download The browser should initiate the download from the server.
Users should be able to pause and resume the download within the browser's download manager.
When a user hits pause, the server should stop/pause sending files.
When a user hits resume, the server should restart sending the file from the last completed percentage, rather than starting from the beginning.
When a user hits cancel, the server should cancel the download.
Multiple users should be able to download files simultaneously.
As a goal reference please check out how Ubuntu download is working: https://ubuntu.com/download/desktop Here download is starting. User can pause, cancel and resume download at any time
router.get('/api/download', (req, res) => {
const root_path = path.join(__dirname, '../', 'download');
const filePath = path.join(root_path, 'big-file.zip');
const fileSize = fs.statSync(filePath).size;
console.log('File size: ' + fileSize);
let start = 0;
let end = fileSize - 1;
const range = req.headers.range;
if (range) {
const parts = range.replace(/bytes=/, '').split('-');
start = parseInt(parts[0], 10);
end = parts[1] ? parseInt(parts[1], 10) : fileSize - 1;
}
const chunkSize = end - start + 1;
let downloadedBytes = 0;
const fileStream = fs.createReadStream(filePath, { start, end });
const headers = {
'Content-Range': `bytes ${start}-${end}/${fileSize}`,
'Accept-Ranges': 'bytes',
'Content-Length': chunkSize,
'Content-Type': 'application/zip',
};
res.writeHead(206, headers);
fileStream.on('data', (chunk) => {
downloadedBytes += chunk.length;
const progress = (downloadedBytes / fileSize) * 100;
console.log(`Download progress: ${progress.toFixed(2)}%`);
res.write(chunk);
});
fileStream.on('end', () => {
res.end();
});
req.on('close', () => {
console.log('Pausing...');
fileStream.destroy();
});
});