Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Download Progress #39

Open
wants to merge 4 commits into
base: master
Choose a base branch
from
Open
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
38 changes: 36 additions & 2 deletions src/structures/Download.js
Original file line number Diff line number Diff line change
Expand Up @@ -17,8 +17,9 @@ module.exports = class Download {
}
}

async writeToDirectory (directory) {
return this.#downloadWorld().then(buffer => fs.writeFile(`${directory}/world${this.fileExtension}`, buffer))
async writeToDirectory (directory, showProgress = false, filename = 'world') {
return (showProgress ? this.#downloadWorldWithProgress() : this.#downloadWorld())
.then(buffer => fs.writeFile(`${directory}/${filename}${this.fileExtension}`, buffer))
}

async getBuffer () {
Expand All @@ -34,4 +35,37 @@ module.exports = class Download {

return await res.buffer()
}

async #downloadWorldWithProgress () {
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

what is this # ?

const res = await fetch(this.downloadUrl, {
headers: (this.token) ? { Authorization: `Bearer ${this.token}` } : {}
})

if (!res.ok) throw new Error(`Failed to download world: ${res.status} ${res.statusText}`)

const totalSize = parseInt(res.headers.get('content-length'), 10)
let downloadedSize = 0

const progressBar = (size) => {
downloadedSize += size
const percentage = ((downloadedSize / totalSize) * 100).toFixed(2)
process.stdout.clearLine()
process.stdout.cursorTo(0)
process.stdout.write(`Progress: [${'#'.repeat((percentage / 10).toFixed(0))}] ${percentage}%`)
}

return new Promise((resolve, reject) => {
const fileChunks = []
res.body
.on('data', (chunk) => {
fileChunks.push(chunk)
progressBar(chunk.length)
})
.on('end', () => {
process.stdout.write('\n')
resolve(Buffer.concat(fileChunks))
})
.on('error', reject)
})
}
}