youtube data api and node.js Error: Required parameter: part - javascript

var fs = require('fs');
var readline = require('readline');
var google = require('googleapis');
var googleAuth = require('google-auth-library');
// If modifying these scopes, delete your previously saved credentials
// at ~/.credentials/youtube-nodejs-quickstart.json
var SCOPES = ['https://www.googleapis.com/auth/youtube.readonly'];
var TOKEN_DIR = (process.env.HOME || process.env.HOMEPATH ||
process.env.USERPROFILE) + '/.credentials/';
var TOKEN_PATH = TOKEN_DIR + 'youtube-nodejs-quickstart.json';
// Load client secrets from a local file.
fs.readFile('client_secret.json', function processClientSecrets(err, content) {
if (err) {
console.log('Error loading client secret file: ' + err);
return;
}
// Authorize a client with the loaded credentials, then call the YouTube API.
authorize(JSON.parse(content), getChannel);
});
/**
* Create an OAuth2 client with the given credentials, and then execute the
* given callback function.
*
* #param {Object} credentials The authorization client credentials.
* #param {function} callback The callback to call with the authorized client.
*/
function authorize(credentials, callback) {
var clientSecret = credentials.installed.client_secret;
var clientId = credentials.installed.client_id;
var redirectUrl = credentials.installed.redirect_uris[0];
var auth = new googleAuth();
var oauth2Client = new auth.OAuth2(clientId, clientSecret, redirectUrl);
// Check if we have previously stored a token.
fs.readFile(TOKEN_PATH, function (err, token) {
if (err) {
getNewToken(oauth2Client, callback);
} else {
oauth2Client.credentials = JSON.parse(token);
callback(oauth2Client);
}
});
}
/**
* Get and store new token after prompting for user authorization, and then
* execute the given callback with the authorized OAuth2 client.
*
* #param {google.auth.OAuth2} oauth2Client The OAuth2 client to get token for.
* #param {getEventsCallback} callback The callback to call with the authorized
* client.
*/
function getNewToken(oauth2Client, callback) {
var authUrl = oauth2Client.generateAuthUrl({
access_type: 'offline',
scope: SCOPES
});
console.log('Authorize this app by visiting this url: ', authUrl);
var rl = readline.createInterface({
input: process.stdin,
output: process.stdout
});
rl.question('Enter the code from that page here: ', function (code) {
rl.close();
oauth2Client.getToken(code, function (err, token) {
if (err) {
console.log('Error while trying to retrieve access token', err);
return;
}
oauth2Client.credentials = token;
storeToken(token);
callback(oauth2Client);
});
});
}
/**
* Store token to disk be used in later program executions.
*
* #param {Object} token The token to store to disk.
*/
function storeToken(token) {
try {
fs.mkdirSync(TOKEN_DIR);
} catch (err) {
if (err.code != 'EEXIST') {
throw err;
}
}
fs.writeFile(TOKEN_PATH, JSON.stringify(token));
console.log('Token stored to ' + TOKEN_PATH);
}
/**
* Lists the names and IDs of up to 10 files.
*
* #param {google.auth.OAuth2} auth An authorized OAuth2 client.
*/
function getChannel(auth) {
var service = google.youtube('v3');
service.channels.list({
auth: auth,
part: 'snippet,contentDetails,statistics',
forUsername: 'GoogleDevelopers'
}, function (err, response) {
if (err) {
console.log('The API returned an error: ' + err);
return;
}
var channels = response.items;
if (channels.length == 0) {
console.log('No channel found.');
} else {
console.log('This channel\'s ID is %s. Its title is \'%s\', and ' +
'it has %s views.',
channels[0].id,
channels[0].snippet.title,
channels[0].statistics.viewCount);
}
});
}
I copied the code from youtube's data API tutorial for node.js
https://developers.google.com/youtube/v3/quickstart/nodejs
I entered the password from the link in the first time.
and now when I run the application I get this output:
The API returned an error: Error: Required parameter: part
this is part
part: 'snippet,contentDetails,statistics',

I guess this is not what you are asking for, but reverting back to version 24.0.0 worked for me:
excerpt from my packages.json
...
"googleapis": "24.0.0",
...

Related

gmail API won't work, cannot deconstruct property 'client_secret'

I tried following the instructions in the gmail tutorial and it won't work.
I downloaded the credentials.json file and index.js file and whenever I run it with node . it gives me the following error:
const {client_secret, client_id, redirect_uris} = credentials.installed;
^
TypeError: Cannot destructure property `client_secret` of 'undefined' or 'null'.
at authorize (/var/www/html/index.js:26:65)
at fs.readFile (/var/www/html/index.js:16:3)
at FSReqWrap.readFileAfterClose [as oncomplete] (internal/fs/read_file_context.js:53:3)
If you check the tutorial Node.js Quickstart
It goes though with you creating the credentials.json file for a web application. Remember to enable the Gmail api.
const fs = require('fs');
const readline = require('readline');
const {google} = require('googleapis');
// If modifying these scopes, delete token.json.
const SCOPES = ['https://www.googleapis.com/auth/gmail.readonly'];
// The file token.json stores the user's access and refresh tokens, and is
// created automatically when the authorization flow completes for the first
// time.
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 Gmail API.
authorize(JSON.parse(content), listLabels);
});
/**
* Create an OAuth2 client with the given credentials, and then execute the
* given callback function.
* #param {Object} credentials The authorization client credentials.
* #param {function} callback The callback to call with the authorized client.
*/
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 getNewToken(oAuth2Client, callback);
oAuth2Client.setCredentials(JSON.parse(token));
callback(oAuth2Client);
});
}
/**
* Get and store new token after prompting for user authorization, and then
* execute the given callback with the authorized OAuth2 client.
* #param {google.auth.OAuth2} oAuth2Client The OAuth2 client to get token for.
* #param {getEventsCallback} callback The callback for the authorized client.
*/
function getNewToken(oAuth2Client, callback) {
const authUrl = oAuth2Client.generateAuthUrl({
access_type: 'offline',
scope: SCOPES,
});
console.log('Authorize this app by visiting this url:', authUrl);
const rl = readline.createInterface({
input: process.stdin,
output: process.stdout,
});
rl.question('Enter the code from that page here: ', (code) => {
rl.close();
oAuth2Client.getToken(code, (err, token) => {
if (err) return console.error('Error retrieving access token', err);
oAuth2Client.setCredentials(token);
// Store the token to disk for later program executions
fs.writeFile(TOKEN_PATH, JSON.stringify(token), (err) => {
if (err) return console.error(err);
console.log('Token stored to', TOKEN_PATH);
});
callback(oAuth2Client);
});
});
}
/**
* Lists the labels in the user's account.
*
* #param {google.auth.OAuth2} auth An authorized OAuth2 client.
*/
function listLabels(auth) {
const gmail = google.gmail({version: 'v1', auth});
gmail.users.labels.list({
userId: 'me',
}, (err, res) => {
if (err) return console.log('The API returned an error: ' + err);
const labels = res.data.labels;
if (labels.length) {
console.log('Labels:');
labels.forEach((label) => {
console.log(`- ${label.name}`);
});
} else {
console.log('No labels found.');
}
});
}
unauthorized_client normally means that you are requesting a scope but you haven't added it in Google developer console. or there is something wrong with the refresh token.
If you have any issues with the authorization try deleting the file in TOKEN_PATH this should cause the authorization window to popup again and you can try again to request access.
Inside your credentials.json file, check if the object key is different than "installed". In my case, the first time I was testing gmail api, I chose "web application" when I created the application on console.developers.google.com/. So, my credentials.json had a "web" key, instead of "installed", which is the one the api page gives you as an example.
You can go back to https://developers.google.com/gmail/api/quickstart/nodejs and click the "Enable the Gmail API" once again, but choose the "Desktop" option this time if you are testing it with at localhost.

Get images from google drive API

I am using node.js to try and get the images out of my google drive. I’ve finished the the getting started and tried to use download to put it in a file. My code is showing that I successfully downloaded it but I can’t see the image the file. I’m fairly new to API’s. I just want to get my image and be able to render it to my page to be viewed. Any help would be very appreciated.
const express = require("express");
const path = require ("path");
const bodyParser = require("body-parser");
const ejs = require("ejs");
const app = express();
app.use(express.static(path.join(__dirname, 'public')));
// Google getting started section
const fs = require('fs');
const readline = require('readline');
const {google} = require('googleapis');
// If modifying these scopes, delete token.json.
const SCOPES = ['https://www.googleapis.com/auth/drive.readonly',
'https://www.googleapis.com/auth/drive.metadata.readonly'];
// The file token.json stores the user's access and refresh tokens, and is
// created automatically when the authorization flow completes for the first
// time.
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,downloadFile);
});
/**
* Create an OAuth2 client with the given credentials, and then execute the
* given callback function.
* #param {Object} credentials The authorization client credentials.
* #param {function} callback The callback to call with the authorized client.
*/
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);
});
}
/**
* Get and store new token after prompting for user authorization, and then
* execute the given callback with the authorized OAuth2 client.
* #param {google.auth.OAuth2} oAuth2Client The OAuth2 client to get token for.
* #param {getEventsCallback} callback The callback for the authorized client.
*/
function getAccessToken(oAuth2Client, callback) {
const authUrl = oAuth2Client.generateAuthUrl({
access_type: 'offline',
scope: SCOPES,
});
console.log('Authorize this app by visiting this url:', authUrl);
const rl = readline.createInterface({
input: process.stdin,
output: process.stdout,
});
rl.question('Enter the code from that page here: ', (code) => {
rl.close();
oAuth2Client.getToken(code, (err, token) => {
if (err) return console.error('Error retrieving access token', err);
oAuth2Client.setCredentials(token);
// Store the token to disk for later program executions
fs.writeFile(TOKEN_PATH, JSON.stringify(token), (err) => {
if (err) return console.error(err);
console.log('Token stored to', TOKEN_PATH);
});
callback(oAuth2Client);
});
});
}
/**
* Lists the names and IDs of up to 10 files.
* #param {google.auth.OAuth2} auth An authorized OAuth2 client.
*/
function listFiles(auth) {
const drive = google.drive({version: 'v3', auth});
drive.files.list({
pageSize: 10,
fields: 'nextPageToken, files(id, name)',
}, (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.map((file) => {
downloadFile(auth);
});
} else {
console.log('No files found.');
}
});
}
// download to local file
function downloadFile(auth) {const drive = google.drive({version: "v3",
auth});
var fileId = "######";
var dest = fs.createWriteStream("public/images/photo.jpg");
drive.files.get({fileId: fileId, alt: "media"}, {responseType: "stream"},
function(err, res){
res.data
.on("end", () => {
})
.on("error", err => {
console.log("Error", err);
})
.pipe(dest);
// I am geeting success but I cant find the Image
console.log("success");
});
}
Not sure if this will solve the issue, but my guess is that the problem is the path where to write the file to. The code itself seems to come straight from the API docs, and seems to be correct.
Based on the official documentation, relative paths start with a slash (/).
So try changing this:
var dest = fs.createWriteStream("public/images/photo.jpg");
With this:
var dest = fs.createWriteStream("/public/images/photo.jpg");
Reference:
Node.js: File System > File paths

Asynchronous webserver in Node

Have a Node webserver(webserver.js) which serves file to clients browser. This webserver uses my file and api require("google-calendar.js");.
What is best practise to serve the google calendar result from Node to the webbrowser?
The webbserver wants to send pages syncronized but the google-api runs asynchronized which currently means result is showing up once the page is reloaded.
Below is the current code for doing this. All kind of feedback is appreciated.
www/index.html:
<html>
<head>
</head>
<body>
<iframe type="text/html" src="calendar.html"></iframe>
</body>
</html>
www/calendar.html:
CONTENT GENERATED BY webserver.js
webserver.js:
var port = 9800;
var serverUrl = "127.0.0.1";
var XMLHttpRequest = require("xmlhttprequest").XMLHttpRequest;
var http = require("http");
var path = require("path");
var fs = require("fs");
var url = require('url');
var checkMimeType = false;
var calendar = require('./google-calendar');
console.log("Starting web server at " + serverUrl + ":" + port);
var calPage = "";
function setCalendarPage(content) {
calPage = content;
console.log("Setting calendar content: " + calPage);
}
http.createServer(function(req, res) {
calendar.getEvents(setCalendarPage);
var request = req;
var filename = req.url;
console.log("====================");
console.log(filename);
if (filename == '/') {
filename = "/index.html";
}
sendFile(filename, res);
}).listen(port, serverUrl);
function getMimeType(filename) {
var ext = path.extname(filename);
var validExtensions = {
".html": "text/html",
".js": "application/javascript",
".css": "text/css",
".txt": "text/plain",
".jpg": "image/jpeg",
".gif": "image/gif",
".png": "image/png",
".woff": "application/font-woff",
".woff2": "application/font-woff2"
};
return validExtensions[ext];
}
function sendFile(filename, res) {
var localPath = __dirname;
localPath += ("/www" + filename);
fs.exists(localPath, function(exists) {
if (exists) {
let mimeType = getMimeType(filename);
getFile(localPath, res, mimeType);
} else {
console.log("File not found: " + localPath);
res.writeHead(404);
res.end();
}
});
}
function getFile(localPath, res, mimeType) {
fs.readFile(localPath, function(err, contents) {
if (!err) {
if (mimeType != undefined) {
res.setHeader("Content-Type", mimeType);
}
res.statusCode = 200;
if (localPath.includes("calendar")) {
var calContent = getHtmlPage(calPage);
res.setHeader("Content-Length", calContent.length);
res.end(calContent);
} else {
res.setHeader("Content-Length", contents.length);
res.end(contents);
}
} else {
res.writeHead(500);
res.end();
}
});
function getHtmlPage(text) {
var html = '<html><head>';
html += '<meta charset="UTF-8">';
html += '<title></title>';
html += '</head>';
html += '<body>';
html += text;
html += '</body>';
html += '</html>';
return html;
}
}
google-calendar.js:
const fs = require('fs');
const mkdirp = require('mkdirp');
const readline = require('readline');
const {google} = require('googleapis');
const OAuth2Client = google.auth.OAuth2;
const SCOPES = ['https://www.googleapis.com/auth/calendar.readonly'];
const TOKEN_PATH = 'credentials.json';
var result = "";
// Load client secrets from a local file.
module.exports = {
getEvents : function (callback){
if(result != ""){
return;
}
fs.readFile('client_secret.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.
return authorize(JSON.parse(content),callback);
});
}
};
/**
* Create an OAuth2 client with the given credentials, and then execute the
* given callback function.
* #param {Object} credentials The authorization client credentials.
* #param {function} callback The callback to call with the authorized client.
*/
function authorize(credentials,callback) {
const {client_secret, client_id, redirect_uris} = credentials.installed;
const oAuth2Client = new OAuth2Client(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));
return listEvents(oAuth2Client, callback);
});
}
/**
* Get and store new token after prompting for user authorization, and then
* execute the given callback with the authorized OAuth2 client.
* #param {google.auth.OAuth2} oAuth2Client The OAuth2 client to get token for.
* #param {getEventsCallback} callback The callback for the authorized client.
*/
function getAccessToken(oAuth2Client, callback) {
const authUrl = oAuth2Client.generateAuthUrl({
access_type: 'offline',
scope: SCOPES,
});
console.log('Authorize this app by visiting this url:', authUrl);
const rl = readline.createInterface({
input: process.stdin,
output: process.stdout,
});
rl.question('Enter the code from that page here: ', (code) => {
rl.close();
oAuth2Client.getToken(code, (err, token) => {
if (err) return callback(err);
oAuth2Client.setCredentials(token);
// Store the token to disk for later program executions
fs.writeFile(TOKEN_PATH, JSON.stringify(token), (err) => {
if (err) console.error(err);
console.log('Token stored to', TOKEN_PATH);
});
callback(oAuth2Client);
});
});
}
/**
* Lists the next 10 events on the user's primary calendar.
* #param {google.auth.OAuth2} auth An authorized OAuth2 client.
*/
function listEvents(auth, callback) {
result = "";
const calendar = google.calendar({version: 'v3', auth});
calendar.events.list({
calendarId: 'primary',
timeMin: (new Date()).toISOString(),
maxResults: 10,
singleEvents: true,
orderBy: 'startTime',
}, (err, {data}) => {
if (err) return console.log('The API returned an error: ' + err);
const events = data.items;
if (events.length) {
console.log('Upcoming 10 events:');
events.map((event, i) => {
const start = event.start.dateTime || event.start.date;
console.log(`${start} - ${event.summary}`);
result += `${start} - ${event.summary} <br>`;
});
callback(result);
} else {
console.log('No upcoming events found.');
}
});
}

javascript & google api : array work only debug mode

I don't understand why my code only works on debug mode. my variable musiques in my function createMusicBox() is an object in debug mode and null in not debuging
var musiques = [];
/**
* Create an OAuth2 client with the given credentials, and then execute the
* given callback function.
*
* #param {Object} credentials The authorization client credentials.
* #param {function} callback The callback to call with the authorized client.
*/
function authorize(credentials, callback) {
var clientSecret = credentials.installed.client_secret;
var clientId = credentials.installed.client_id;
var redirectUrl = credentials.installed.redirect_uris[0];
var auth = new googleAuth();
var oauth2Client = new auth.OAuth2(clientId, clientSecret, redirectUrl);
// Check if we have previously stored a token.
fs.readFile(TOKEN_PATH, function(err, token) {
if (err) {
getNewToken(oauth2Client, callback);
} else {
oauth2Client.credentials = JSON.parse(token);
callback(oauth2Client);
}
});
}
/**
* Lists the names and IDs of up to 10 files.
*
* #param {google.auth.OAuth2} auth An authorized OAuth2 client.
*/
function listFiles(auth) {
var service = google.drive('v3');
service.files.list({
auth: auth,
pageSize: 10,
fields: "nextPageToken, files(id, name)"
}, function(err, response) {
if (err) {
console.log('The API returned an error: ' + err);
return;
}
var files = response.files;
if (files.length == 0) {
console.log('No files found.');
} else {
musiques=files;
console.log('Files:');
for (var i = 0; i < files.length; i++) {
musiques[i] = files[i];
var file = files[i];
console.log('%s (%s)', file.name, file.id);
}
}
});
}
// this function pulls music in my google drive
function createMusicBox() {
// Load client secrets from a local file.
fs.readFile('client_secret.json', function processClientSecrets(err, content) {
if (err) {
console.log('Error loading client secret file: ' + err);
return;
}
// Authorize a client with the loaded credentials, then call the Drive API.
authorize(JSON.parse(content), listFiles);
});
console.log(musiques);
}
I find a solution, i put a callback in listFiles and now it works perfectly
function createMusicBox(event) {
// Load client secrets from a local file.
fs.readFile('client_secret.json', function processClientSecrets(err, content) {
if (err) {
console.log('Error loading client secret file: ' + err);
return;
}
// Authorize a client with the loaded credentials, then call the Drive API.
authorize(JSON.parse(content), listFiles, event);
});
}
function getNewToken(oauth2Client, callback) {
var authUrl = oauth2Client.generateAuthUrl({
access_type: 'offline',
scope: SCOPES
});
console.log('Authorize this app by visiting this url: ', authUrl);
var rl = readline.createInterface({
input: process.stdin,
output: process.stdout
});
rl.question('Enter the code from that page here: ', function(code) {
rl.close();
oauth2Client.getToken(code, function(err, token) {
if (err) {
console.log('Error while trying to retrieve access token', err);
return;
}
oauth2Client.credentials = token;
storeToken(token);
callback(oauth2Client);
});
});
}
function listFiles(auth, callback, event) {
var service = google.drive('v3');
service.files.list({
auth: auth,
pageSize: 10,
fields: "nextPageToken, files(id, name)"
}, function(err, response, listMusic) {
if (err) {
console.log('The API returned an error: ' + err);
return;
}
var files = response.files;
if (files.length == 0) {
console.log('No files found.');
} else {
callback(event, files);
}
});
}

When making multiple calls to google sheets API authentication doesn't work for second call: Request had insufficient authentication scopes

So basically what I've done here is I've hijacked the google sheets api node.js quickstart guide for my own purposes. Everything in here works great up until it hits my spreadsheets.batchUpdate and then everything gets wacky.
If I comment out the "auth" initialization in spreadsheets.batchUpdate I get the error message: The API returned an error: Error: The request does not have valid authentication credentials.
If I comment out the "auth" initialization in spreadsheets.batchUpdate I get the error message: The API returned an error: Error: Request had insufficient authentication scopes.
All I'm trying to do with these calls is get some data out of the sheet and then delete the rows after but I can't figure out this authentication issue.
var fs = require('fs');
var updateDB = require('./updateDB.js');
var readline = require('readline');
var google = require('googleapis');
var googleAuth = require('google-auth-library');
var splitData;
// If modifying these scopes, delete your previously saved credentials
// at ~/.credentials/sheets.googleapis.com-nodejs-quickstart.json
var SCOPES = ['https://www.googleapis.com/auth/spreadsheets.readonly'];
var TOKEN_DIR = (process.env.HOME || process.env.HOMEPATH ||
process.env.USERPROFILE) + '/.credentials/';
var TOKEN_PATH = TOKEN_DIR + 'sheets.googleapis.com-nodejs-quickstart.json';
var array = [];
var run = {
runQuickstart : function() {
// Load client secrets from a local file.
fs.readFile('client_secret.json', function processClientSecrets(err, content) {
if (err) {
console.log('Error loading client secret file: ' + err);
return;
}
// Authorize a client with the loaded credentials, then call the
// Google Sheets API.
authorize(JSON.parse(content), listMajors);
});
}
}
/**
* Create an OAuth2 client with the given credentials, and then execute the
* given callback function.
*
* #param {Object} credentials The authorization client credentials.
* #param {function} callback The callback to call with the authorized client.
*/
function authorize(credentials, callback) {
var clientSecret = credentials.installed.client_secret;
var clientId = credentials.installed.client_id;
var redirectUrl = credentials.installed.redirect_uris[0];
var auth = new googleAuth();
var oauth2Client = new auth.OAuth2(clientId, clientSecret, redirectUrl);
// Check if we have previously stored a token.
fs.readFile(TOKEN_PATH, function(err, token) {
if (err) {
getNewToken(oauth2Client, callback);
} else {
oauth2Client.credentials = JSON.parse(token);
callback(oauth2Client);
}
});
}
/**
* Get and store new token after prompting for user authorization, and then
* execute the given callback with the authorized OAuth2 client.
*
* #param {google.auth.OAuth2} oauth2Client The OAuth2 client to get token for.
* #param {getEventsCallback} callback The callback to call with the authorized
* client.
*/
function getNewToken(oauth2Client, callback) {
var authUrl = oauth2Client.generateAuthUrl({
access_type: 'offline',
scope: SCOPES
});
console.log('Authorize this app by visiting this url: ', authUrl);
var rl = readline.createInterface({
input: process.stdin,
output: process.stdout
});
rl.question('Enter the code from that page here: ', function(code) {
rl.close();
oauth2Client.getToken(code, function(err, token) {
if (err) {
console.log('Error while trying to retrieve access token', err);
return;
}
oauth2Client.credentials = token;
storeToken(token);
callback(oauth2Client);
});
});
}
/**
* Store token to disk be used in later program executions.
*
* #param {Object} token The token to store to disk.
*/
function storeToken(token) {
try {
fs.mkdirSync(TOKEN_DIR);
} catch (err) {
if (err.code != 'EEXIST') {
throw err;
}
}
fs.writeFile(TOKEN_PATH, JSON.stringify(token));
console.log('Token stored to ' + TOKEN_PATH);
}
/**
* Print the names and majors of students in a sample spreadsheet:
* https://docs.google.com/spreadsheets/d/1BxiMVs0XRA5nFMdKvBdBZjgmUUqptlbs74OgvE2upms/edit
*/
function listMajors(auth) {
var sheets = google.sheets('v4');
sheets.spreadsheets.values.get({
auth: auth,
spreadsheetId: '1EV8S8AaAmxF3vP0F6RWxKIUlvF6uFEmsrOFWA1oNBYI',
range: 'Form Responses 1!A3:X3',
}, function(err, response) {
if (err) {
console.log('The API returned an error: ' + err);
return;
}
var rows = response.values;
//splitData = rows.split(',');
updateDB.inputFormToDB.apply(this, rows);
if (rows.length == 0) {
console.log('No data found.');
} else {
console.log('Form Responses');
for (var i = 0; i < rows.length; i++) {
var row = rows[i];
// Print columns A and E, which correspond to indices 0 and 4.
console.log('%s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s', row[0], row[1], row[2], row[3], row[4], row[5], row[6], row[7], row[8], row[9],row[10], row[11], row[12], row[13], row[14], row[15], row[16], row[17], row[18], row[19], row[20], row[21], row[22], row[23]);
}
var spreadsheetId = '1EV8S8AaAmxF3vP0F6RWxKIUlvF6uFEmsrOFWA1oNBYI';
var requests = [];
requests.push({
"deleteDimension": {
"range": {
"sheetId": spreadsheetId,
"dimension": "ROWS",
"startIndex": 0,
"endIndex": 3
}
}
});
var batchUpdateRequest = {requests: requests}
var test = auth;
sheets.spreadsheets.batchUpdate({
// auth: test,
spreadsheetId: spreadsheetId,
resource: batchUpdateRequest
}, function(err, response) {
if (err) {
console.log('The API returned an error: ' + err);
return;
}
});
}
});
}
module.exports = run;
https://www.googleapis.com/auth/spreadsheets.readonly will give you read rights.
You need to use the https://www.googleapis.com/auth/spreadsheets scope to update the sheet.
https://www.googleapis.com/auth/spreadsheets.readonly
Allows read-only access to the user's sheets and their properties.
https://www.googleapis.com/auth/spreadsheets
Allows read/write access to the user's sheets and their properties.

Categories

Resources