diff --git a/src/models/file.js b/src/models/file.js index 20ce5cf..e54d11a 100644 --- a/src/models/file.js +++ b/src/models/file.js @@ -76,31 +76,31 @@ class File { return reject(response.statusMessage); } - // Get the content length and parse it to an integer - const contentLength = parseInt(response.headers['content-length'], 10); - emitter.emit('download.started', { url: this.url, filepath: this.filepath, length: contentLength }); + + emitter.emit('download.started', { url: this.url, filepath: this.filepath }); - const step = Math.floor(contentLength / 100); - let stepLimit = step; // Create a variable to hold the downloaded size let downloaded = 0; // Handle response data + let i = 0; response.on('data', (chunk) => { - // Add the size of the chunk to the downloaded variable downloaded += chunk.length; + i++; // Check if the downloaded size is bigger than the step limit - if (downloaded > stepLimit) { + if (i === 500) { // Emit a download.progress event with the url, filepath and downloaded size - emitter.emit('download.progress', { url: this.url, filepath: this.filepath, percentage: Math.floor((downloaded / contentLength) * 100) }); - stepLimit += step; + emitter.emit('download.progress', { url: this.url, filepath: this.filepath, downloaded }); + i = 0; } }); response.pipe(file); - file.on('finish', () => { + file.on('finish', () => { + emitter.emit('download.progress', { url: this.url, filepath: this.filepath, downloaded }); + // Emit a download.end event with the url and filepath emitter.emit('download.end', { url: this.url, filepath: this.filepath }); file.close(() => { diff --git a/src/subscribers/consoleSubscriber.js b/src/subscribers/consoleSubscriber.js index 369dbea..c967750 100644 --- a/src/subscribers/consoleSubscriber.js +++ b/src/subscribers/consoleSubscriber.js @@ -14,8 +14,8 @@ emitter.on('download.start', ({ url, filepath }) => { }); // Create a new listener for the download.start event -emitter.on('download.started', ({ url, filepath, length }) => { - log('download.started', `Downloading to ${filepath} and length is ${length}`); +emitter.on('download.started', ({ url, filepath }) => { + log('download.started', `Downloading to ${filepath}`); }); // Create a new listener for the download.end event @@ -29,8 +29,8 @@ emitter.on('download.error', ({ url, filepath, error, type }) => { }); // Create a new listener for the download.progress event -emitter.on('download.progress', ({ url, filepath, percentage }) => { - log('download.progress', `Downloaded ${percentage}% to ${filepath}`); +emitter.on('download.progress', ({ url, filepath, downloaded }) => { + log('download.progress', `Downloaded [${(Math.floor(downloaded / 1024 / 1024 * 100) / 100).toLocaleString()} Mo] to ${filepath}`); });