Vous êtes sur la page 1sur 22

11/16/2018 CRUD operation on Google Spreadsheet using NodeJS – Agira Technologies – Medium

Images haven’t loaded yet. Please exit printing, wait for images to load, and try to print again.
Agira Technologies Follow
Leading web development company in India. Expert in creating web application( Ruby on Rails,
Golang, Laravel, Symfony, PHP, MEAN Stack) & mobile app development
Aug 16 · 6 min read

CRUD operation on Google Spreadsheet


using NodeJS

We all must have heard about CRUD(Create, Retrieve, Update and


Delete) operation. In this blog, let’s see how we can do CRUD operation
on Google Spreadsheet using Node.js,

When we are going to implement APIs,

https://medium.com/@agiratech/crud-operation-on-google-spreadsheet-using-nodejs-a0a8dbb58c95 1/22
11/16/2018 CRUD operation on Google Spreadsheet using NodeJS – Agira Technologies – Medium

What is Google Spreadsheet?


Google Spreadsheets is a Web-based application that allows users to
create, update and modify spreadsheets and share the data live online.
The Ajax-based program is compatible with Microsoft Excel and CSV
(comma-separated values) les. Spreadsheets can also be saved as
HTML.

What exactly is Node JS?


Node.js is an open-source, cross-platform JavaScript run-time
environment that executes JavaScript code server-side.

The Node run-time environment includes everything you need to


execute a program written in JavaScript.

Node.js came into existence when the original developers of JavaScript


extended it from something you could only run in the browser to
something you could run on your machine as a standalone application.

Now you can do much more with JavaScript than just making websites
interactive.

Prerequisites
To run this simple example, all you’ll need is

https://medium.com/@agiratech/crud-operation-on-google-spreadsheet-using-nodejs-a0a8dbb58c95 2/22
11/16/2018 CRUD operation on Google Spreadsheet using NodeJS – Agira Technologies – Medium

Node.js & npm installed and a Google account.

Step 1: Turn on the Google Sheets API &


Create the credentials le
Step 1.1: Use this URL link to create a new console project.

Step 1.2: To enable the spreadsheet API, please check the screenshot.

https://medium.com/@agiratech/crud-operation-on-google-spreadsheet-using-nodejs-a0a8dbb58c95 3/22
11/16/2018 CRUD operation on Google Spreadsheet using NodeJS – Agira Technologies – Medium

Step 1.3: In search box, type the word google sheet and click the card to
enable the spreadsheet API

https://medium.com/@agiratech/crud-operation-on-google-spreadsheet-using-nodejs-a0a8dbb58c95 4/22
11/16/2018 CRUD operation on Google Spreadsheet using NodeJS – Agira Technologies – Medium

Step 1.4: Once the google spreadsheet API enables, then you need to
create credentials, Use this URL link to create a credentials

Step 1.5: then click the “create credentials” from the dropdown and
select the OAuth client ID.

READ NOW >> Getting Started With Sails.js

https://medium.com/@agiratech/crud-operation-on-google-spreadsheet-using-nodejs-a0a8dbb58c95 5/22
11/16/2018 CRUD operation on Google Spreadsheet using NodeJS – Agira Technologies – Medium

Step 1.6: Select the checkbox “other” option and click the create.

Step 1.7: then download the credentials le and we can use this le in
our sample code.

https://medium.com/@agiratech/crud-operation-on-google-spreadsheet-using-nodejs-a0a8dbb58c95 6/22
11/16/2018 CRUD operation on Google Spreadsheet using NodeJS – Agira Technologies – Medium

Step 2: Install The Client Library


Run the following commands to install the libraries using npm:

$ npm install googleapis@27 --save

Related: How To Deploy NodeJS App to Heroku

Step 3: Set up the sample in NodeJS

https://medium.com/@agiratech/crud-operation-on-google-spreadsheet-using-nodejs-a0a8dbb58c95 7/22
11/16/2018 CRUD operation on Google Spreadsheet using NodeJS – Agira Technologies – Medium

Create a ".js” file in your working directory and here i


named it like "spreadsheet.js" and copy the following code:

var fs = require('fs');

var readline = require('readline');

var google = require('googleapis');

var googleAuth = require('google-auth-library');

var SCOPES =
['https://www.googleapis.com/auth/spreadsheets'];

var TOKEN_PATH = './.credentials/token.json'; // first time


if you run the sample code this file will generate,

Var SPREADSHEET_JSON_FILE = ‘download the credentials file


***.json’ //use the download the credentials file here

// Store token to disk be used in later program executions.

function storeToken(token) {

try {

fs.mkdirSync(TOKEN_DIR);

} catch (err) {

if (err.code !== 'EEXIST') {

throw err;

https://medium.com/@agiratech/crud-operation-on-google-spreadsheet-using-nodejs-a0a8dbb58c95 8/22
11/16/2018 CRUD operation on Google Spreadsheet using NodeJS – Agira Technologies – Medium

fs.writeFile(TOKEN_PATH, JSON.stringify(token));

console.log('Token stored to ' + TOKEN_PATH);

// Get and store new token after prompting for user


authorization, and then

// execute the given callback with the authorized OAuth2


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,

https://medium.com/@agiratech/crud-operation-on-google-spreadsheet-using-nodejs-a0a8dbb58c95 9/22
11/16/2018 CRUD operation on Google Spreadsheet using NodeJS – Agira Technologies – Medium

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

});

});

https://medium.com/@agiratech/crud-operation-on-google-spreadsheet-using-nodejs-a0a8dbb58c95 10/22
11/16/2018 CRUD operation on Google Spreadsheet using NodeJS – Agira Technologies – Medium

// Create an OAuth2 client with the given credentials, and


then execute the given callback function.

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

});

https://medium.com/@agiratech/crud-operation-on-google-spreadsheet-using-nodejs-a0a8dbb58c95 11/22
11/16/2018 CRUD operation on Google Spreadsheet using NodeJS – Agira Technologies – Medium

Also Read: 10 JavaScript concepts every Node.js developer should


know

READ NOW >> Guide to Create Reusable Bundle in Symfony2

Step 3.1: CREATE (or) UPDATE


CREATE or UPDATE both the operations can be done by the below
mentioned code so copy and paste this code for applying both,

var create = function () {

function listMajors(auth) {

var sheets = google.sheets('v4');

var SPREADSHEET_ID = "************";

var range = "**********";

var requestInsert = {

auth: auth,

https://medium.com/@agiratech/crud-operation-on-google-spreadsheet-using-nodejs-a0a8dbb58c95 12/22
11/16/2018 CRUD operation on Google Spreadsheet using NodeJS – Agira Technologies – Medium

spreadsheetId: SPREADSHEET_ID,

range: range,

valueInputOption: 'RAW',

resource : {

range: range,

'majorDimension': 'ROWS',

'values': [["name","list"]]
}

};

sheets.spreadsheets.values.update(requestInsert,
function(err, response) {

if (err) {

throw err;

console.log(response,' record Inserted.');

});

// Load client secrets from a local file.

https://medium.com/@agiratech/crud-operation-on-google-spreadsheet-using-nodejs-a0a8dbb58c95 13/22
11/16/2018 CRUD operation on Google Spreadsheet using NodeJS – Agira Technologies – Medium

fs.readFile(SPREADSHEET_JSON_FILE, 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);

});

// TODO: create operation

create();

Step 3.1: READ

https://medium.com/@agiratech/crud-operation-on-google-spreadsheet-using-nodejs-a0a8dbb58c95 14/22
11/16/2018 CRUD operation on Google Spreadsheet using NodeJS – Agira Technologies – Medium

var Read = function () {

function listMajors(auth) {

var sheets = google.sheets('v4');

var SPREADSHEET_ID = "************";

var range = "**********";

var request = {

auth: auth,

spreadsheetId: SPREADSHEET_ID,

range: range

};

//To get all rows form spreadsheet

sheets.spreadsheets.values.get(request, function(err,
response) {

if (err) {

throw err;

console.log(response,' records.');

https://medium.com/@agiratech/crud-operation-on-google-spreadsheet-using-nodejs-a0a8dbb58c95 15/22
11/16/2018 CRUD operation on Google Spreadsheet using NodeJS – Agira Technologies – Medium

});

// Load client secrets from a local file.

fs.readFile(SPREADSHEET_JSON_FILE, 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);

});

//TODO: read operation

Read()

https://medium.com/@agiratech/crud-operation-on-google-spreadsheet-using-nodejs-a0a8dbb58c95 16/22
11/16/2018 CRUD operation on Google Spreadsheet using NodeJS – Agira Technologies – Medium

Step 3.1: DELETE

var delete = function () {

// Print the names and majors of students in a sample


spreadsheet:

function listMajors(auth) {

var sheets = google.sheets('v4');

var SPREADSHEET_ID = "************";

var range = "**********";

var sheetId = "****";

var deleteRequest = {

auth: auth,

spreadsheetId: process.env.SPREADSHEET_ID,

resource : {

'requests': [

'deleteDimension': {

https://medium.com/@agiratech/crud-operation-on-google-spreadsheet-using-nodejs-a0a8dbb58c95 17/22
11/16/2018 CRUD operation on Google Spreadsheet using NodeJS – Agira Technologies – Medium

'range': {

'sheetId': sheetId,

'dimension': 'ROWS',

'startIndex': range,

'endIndex': range+1

]
},

};

sheets.spreadsheets.batchUpdate(deleteRequest, function(err,
response) {

if (err) {console.log(err);}

console.log(response,'Deleted');

});

// Load client secrets from a local file.

https://medium.com/@agiratech/crud-operation-on-google-spreadsheet-using-nodejs-a0a8dbb58c95 18/22
11/16/2018 CRUD operation on Google Spreadsheet using NodeJS – Agira Technologies – Medium

fs.readFile(SPREADSHEET_JSON_FILE, 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);

});

//TODO: Delete operation

delete()

READ NOW >> Tips To Improve The Performance Of A Laravel


Application

https://medium.com/@agiratech/crud-operation-on-google-spreadsheet-using-nodejs-a0a8dbb58c95 19/22
11/16/2018 CRUD operation on Google Spreadsheet using NodeJS – Agira Technologies – Medium

Step 4: Run the sample

$ node spreadsheet.js

Note: Access permission

The rst time you run the sample, it will prompt you to authorize
access:

Browse to the provided URL in your web browser.

If you have not logged into your Google account, then you will be
prompted to log in. If you are logged into multiple Google accounts,
then you will be asked to select one account to use for the
authorization.

Now, click the Accept button.

Copy the given code, paste it into the command-line prompt, and press
Enter.

That’s all guys! We done it. Here we used NodeJS and we can also use
“Google App Script” to apply this CRUD operation. If you’re interested
to know then let us know your opinions in comment box, will surely
discuss about it in coming days.

https://medium.com/@agiratech/crud-operation-on-google-spreadsheet-using-nodejs-a0a8dbb58c95 20/22
11/16/2018 CRUD operation on Google Spreadsheet using NodeJS – Agira Technologies – Medium

Mad over reading? Then never miss out anything from our blog works,
there you can read about all latest technologies & it’s updates which
would be perfect for your 15 minutes tea break! What else guys hit the
subscribe link and go crazy over learning.

https://medium.com/@agiratech/crud-operation-on-google-spreadsheet-using-nodejs-a0a8dbb58c95 21/22
11/16/2018 CRUD operation on Google Spreadsheet using NodeJS – Agira Technologies – Medium

https://medium.com/@agiratech/crud-operation-on-google-spreadsheet-using-nodejs-a0a8dbb58c95 22/22

Vous aimerez peut-être aussi