Google-api-nodejs-client: TypeError: Cannot read property 'data' of undefined on the sample code....

Created on 14 Sep 2018  路  16Comments  路  Source: googleapis/google-api-nodejs-client

Trying to run the sample code for the drive list stuff and am getting this error:

TypeError: Cannot read property 'data' of undefined
at runSample (c:\Users\Konstantin\Desktop\USN\JS\newCode.js:15:19)
at <anonymous>
at process._tickCallback (internal/process/next_tick.js:188:7)

Environment details

  • OS: Windows 10
  • Node.js version: 8.11.4
  • npm version: 6.4.1
  • googleapis version: 33.0.0

Steps to reproduce

  1. Run the Drive list sample code......

Bonus question:
How can I create a token to use so that I don't have to login each time the script is run?

needs more info question

Most helpful comment

Sure thing! :)
I just have it inside VS Code and press the run button tbh... But here is the script:

'use strict';

const {google} = require('googleapis');
const sampleClient = require('./sampleclient');

const drive = google.drive({
  version: 'v3',
  auth: sampleClient.oAuth2Client
});

async function runSample (query) {
  const params = { 
      pageSize: 3,
      fields: "files(id, name, parents, size)"
    };
  params.q = query;
  const res = await drive.files.list(params);
  console.log(res.data);
  return res.data;
}

if (module === require.main) {
  const scopes = ['https://www.googleapis.com/auth/drive'];
  sampleClient.authenticate(scopes)
    .then(c => runSample())
    .catch(console.error);
}

module.exports = {
  runSample,
  client: sampleClient.oAuth2Client
};

It gets executed with node newCode.js

All 16 comments

Greetings! I need a few more details :) Even though it's the sample, can you share the code you're running? And exactly how you're running it? This works for me locally, and I can't quite imagine how the drive list sample would give that error :)

Sure thing! :)
I just have it inside VS Code and press the run button tbh... But here is the script:

'use strict';

const {google} = require('googleapis');
const sampleClient = require('./sampleclient');

const drive = google.drive({
  version: 'v3',
  auth: sampleClient.oAuth2Client
});

async function runSample (query) {
  const params = { 
      pageSize: 3,
      fields: "files(id, name, parents, size)"
    };
  params.q = query;
  const res = await drive.files.list(params);
  console.log(res.data);
  return res.data;
}

if (module === require.main) {
  const scopes = ['https://www.googleapis.com/auth/drive'];
  sampleClient.authenticate(scopes)
    .then(c => runSample())
    .catch(console.error);
}

module.exports = {
  runSample,
  client: sampleClient.oAuth2Client
};

It gets executed with node newCode.js

Hmmmm - I am wondering if you're running an old version of node.js inside of vscode. It's weird that data on the res object is undefined, and really makes me wonder if this is somehow running in node.js 6. scratches head

Honestly it could be; I am not a VS Code pro 馃槀 do you know of any way to check this (and potentially fix?) or to run the code properly?

Well just to start - can you try running node newCode.js from the command line outside of vscode?

image

Thanks! And the results of node --version?

It shows 8.11.4

image

And my packages:

image

Ahhhh. That's a pretty old version of googleapis :) Can you please upgrade to 33, and remove the dependency on google-auth-library?

Just found my error....

I had a googleapis@27 installed due to the quickstart guide:
https://developers.google.com/drive/api/v3/quickstart/nodejs

People: check your versions :)

Ahhhh. That's a pretty old version of googleapis :) Can you please upgrade to 33, and remove the dependency on google-auth-library?

Yeah, just did :D

I'm getting the same error, and I have googleapis version 39.2.0

Please file a new issue with details :)

Hello Justin
could you help me with this please?
I'm coding a program to download all file in my Google Drive at once.
When there're a few of them (4 to 5), everything goes well. However, when there're 10, 18 files or more, I receive the following message:
"TypeError: Cannot read property 'data' of undefined".

This is the source code, (I've added some try/catch trying to figure out where was the problem. I've also added several async/await in my convincement the problem comes from the improper management of the async nature of Node.js)

const fs = require('fs');
const readline = require('readline');
const {google} = require('googleapis');

const pdfedition = require('./pdfEdition')
const addressDB = require('./db')

const SCOPES = ['https://www.googleapis.com/auth/drive.metadata.readonly'];

const TOKEN_PATH = 'token.json';

// Load client secrets from a local file.
fs.readFile('credentials.json', (err, content) => {
if (err) return console.log('Error loading client secret file:', err);
// Authorize a client with credentials, then call the Google Drive API.

authorize(JSON.parse(content), listFiles);
});

function authorize(credentials, callback) {
const {client_secret, client_id, redirect_uris} = credentials.installed;
const oAuth2Client = new google.auth.OAuth2(
client_id, client_secret, redirect_uris[0]);

// Check if we have previously stored a token.
fs.readFile(TOKEN_PATH, (err, token) => {
if (err)
return getAccessToken(oAuth2Client, callback);
oAuth2Client.setCredentials(JSON.parse(token));
callback(oAuth2Client);
});
}

// Lists the names and IDs of our files.
function listFiles(auth) {
var filesArray = new Array;
const drive = google.drive({version: 'v3', auth});
drive.files.list({
q: "mimeType='application/pdf'", // Download only PDF files
pageSize: 100,
spaces: 'drive',
fields: 'nextPageToken, files(id, name, fileExtension, createdTime)',
}, (err, res) => {
if (err) return console.log('The API returned an error: ' + err);
const files = res.data.files;
if (files.length) {
console.log('Files:'+ files.length);
files.map((file) => {
filesArray.push(file.id)
try {
var i = filesArray.indexOf(file.id);
downloadFiles(auth, file.id, file.name, i)
}catch (error){
console.log(error);
}
});
} else {
console.log('No files found.');
}
});
}

async function downloadFiles(auth, fileId, fileName, fileNumber) {
const trackingString = '123456789';
const printMode = 'ABC';
var tempBuffer = [];
const drive = google.drive({ version: 'v3', auth });
drive.files.get({fileId: fileId, alt: 'media'}, {responseType: 'stream'},
function(err, res){
try{
res.data
.on('end', () => {
var pdfBuffer = Buffer.concat(tempBuffer);
pdfedition.insertInfoIntoPdf(pdfBuffer, fileName, trackingString, printMode, addressDB.addressDB[fileNumber]);
console.log(Downloaded file -> ${fileName} ${fileId});
})
.on('error', err => {
console.log('Error', err);
})
.on('data', function (chunk) {
tempBuffer.push(chunk);
})
}catch(err){
console.log('Captured error: ' + err);
}
}
);
};

Was this page helpful?
0 / 5 - 0 ratings

Related issues

JustinBeckwith picture JustinBeckwith  路  3Comments

skiod picture skiod  路  3Comments

rainabba picture rainabba  路  4Comments

suparnavg picture suparnavg  路  3Comments

eduDorus picture eduDorus  路  3Comments