Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Node Googleapis Drive Get File Url With Await

Here is my code;

await GoogleDriveService.files.get({
        fileId: id,
        alt: 'media'
    }, {
        responseType: 'arraybuffer',
        encoding: null
    }, function(err, response) {
        if (err) {
            // logger.system.warn(err)
        } else {
            var imageType = response.headers['content-type'];
            var base64 = Buffer(response.data, 'utf8').toString('base64');
            var dataURI = 'data:' + imageType + ';base64,' + base64;
            return dataURI;
        }
    });

But await is not working. I’m using inside function and function return undefined before dataURI veriable. What should I do?

Here is my full function;

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

const uploadImage = async (filePath,name,mimeType) => {
    const response = await GoogleDriveService.files.create({
        requestBody: {
            name,
            mimeType,
        },
        media: {
            mimeType,
            body: fs.createReadStream(filePath),
        },
    }); 
    
    await GoogleDriveService.files.get({
        fileId: response.data.id,
        alt: 'media'
    }, {
        responseType: 'arraybuffer',
        encoding: null
    }, function(err, response) {
        var imageType = response.headers['content-type'];
        var base64 = Buffer(response.data, 'utf8').toString('base64');
        var dataURI = 'data:' + imageType + ';base64,' + base64;
        return dataURI;
    });
}

>Solution :

await is for promises, which are an alternative to callback functions. Both are ways to handle asynchronous operations like files.get.

You must omit the third argument (the callback function) from the files.get call if you want to await the result.

var response = await GoogleDriveService.files.get({
  fileId: id,
  alt: 'media'
}, {
  responseType: 'arraybuffer',
  encoding: null
});
var imageType = response.headers['content-type'];
var base64 = Buffer(response.data, 'utf8').toString('base64');
var dataURI = 'data:' + imageType + ';base64,' + base64;
return dataURI;
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading