Skip to content

Instantly share code, notes, and snippets.

@rawars
Created June 20, 2020 21:00
Show Gist options
  • Save rawars/d920401612c44f35eff0f072e2a18bdb to your computer and use it in GitHub Desktop.
Save rawars/d920401612c44f35eff0f072e2a18bdb to your computer and use it in GitHub Desktop.
function download(file) {
		return new Promise( async (resolve, reject) => {
			const fileId = file;
			const destPath = path.resolve(__dirname, '../temp/' + file.name + '.pdf');
			const dest = fs.createWriteStream(destPath);

			const res = await this.drive.files.export({
				auth: this.jwToken,
				fileId: fileId, // fileId,
				parents: ['1m5iHJC5nlESZc6QkFUBW8zClS7zhv8Pj'],
				mimeType: 'application/pdf'
			}, { responseType: 'stream' });

			await Promise.all([
				new Promise((resolve, reject) => {
					res.data
						.on('end', () => {
							console.log(`Done downloading document: ${destPath}.`);
							resolve('end');
						})
						.on('error', err => {
							console.error('Error downloading document.');
							reject(err);
						})
						.pipe(dest);
				}),
				new Promise((resolve, reject) => {
					dest
						.on('finish', () => {
							console.log(`Done saving document: ${destPath}.`);
							resolve('finish');
						})
						.on('error', err => {
							console.error('Error saving document.');
							reject(err);
						})
				})
			]).then(()=>{
				resolve()
			})
		})
	}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment