Home > Blockchain >  Node Googleapis Drive Get File Url With Await
Node Googleapis Drive Get File Url With Await

Time:08-08

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;

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;
    });
}

CodePudding user response:

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;
  • Related