Background
Google doc has become one of those tools we use in our daily life. It has a great features to manage documents. It is easily accessible and can be shared with anyone to collaborate.
In case you didn't know, google has an API to read and write google doc contents. We can use this API for many use cases like importing data from google doc to our application, export application data to google doc depending on our requirements.
In this article we are going to setup a node.js server which will interact with googleapi to read/write google docs data.
Before we begin, we must have a google doc ID which is string before /edit
when you open a google doc in browser.
Eg: https://docs.google.com/document/d/{google_doc_id}/edit
Now lets follow the steps given below:
Setup and Execution
Step 1: Setup project and store google doc ID.
Run following commands in order to setup an app.
mkdir google-docs
cd google-docs
npm init -y
git init
touch .gitignore
npm i googleapis config
mkdir src && touch src/auth.js
mkdir config && touch config/local.json
Inside .gitignore file, paste following code so that they won't get uploaded to git repository.
node_modules/
config/
credentials.json
token.json
Inside config/local.json
file paste following code:
{
"google": {
"doc_id": "YOUR_GOOGLE_DOC_ID"
}
}
Step 2: Enable google doc and gmail API.
Go to link given below and click on Enable button.
https://console.developers.google.com/apis/library/docs.googleapis.com
Go to link given below and click on Enable Gmail API.
https://developers.google.com/gmail/api/quickstart/nodejs
Get credentials.json file and store it in your project root directory i.e. google-docs
in our case.
Step 3: Inside src/auth.js
insert following code:
Here, we are authorizing our app to get token.json file from google.
const fs = require("fs");
const readline = require("readline");
const { google } = require("googleapis");
const SCOPES = ["https://www.googleapis.com/auth/documents"];
// 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), () => console.log("authorized!"));
});
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);
});
}
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), (error) => {
if (error) return console.error(error);
console.log("Token stored to", TOKEN_PATH);
});
callback(oAuth2Client);
});
});
}
Now run node src/auth.js
inside project directory and follow the prompt in terminal.
After authorizing, you will have a token.json
file in project root directory.
And if you run node src/auth.js
you will see authorized!
message in terminal
Great! our app is authorized, now we can write message in google doc.
Step 4: Write data inside google doc:
Create write.js
inside src folder and paste following code.
const { google } = require("googleapis");
const token = require("../token.json");
const credentials = require("../credentials.json");
const config = require("config");
function authorize() {
const { client_secret, client_id, redirect_uris } = credentials.installed;
const oAuth2Client = new google.auth.OAuth2(
client_id,
client_secret,
redirect_uris[0]
);
oAuth2Client.setCredentials(token);
return oAuth2Client;
}
async function main(DOC_ID) {
const auth = await authorize();
const docs = google.docs({
version: "v1",
auth,
});
await docs.documents.batchUpdate({
auth,
documentId: DOC_ID,
requestBody: {
requests: [
{
insertText: {
location: {
index: 1,
},
text: "hello world.!\n",
},
},
],
},
});
console.log("========data written successfully.===========");
}
main(config.get("google.doc_id"));
Now run node src/write.js
and you will have hello world
data written in your google doc.
Step 5: Read data from google docs.
Create read.js
inside src folder and paste following code.
const { google } = require("googleapis");
const token = require("../token.json");
const credentials = require("../credentials.json");
const config = require("config");
function authorize() {
const { client_secret, client_id, redirect_uris } = credentials.installed;
const oAuth2Client = new google.auth.OAuth2(
client_id,
client_secret,
redirect_uris[0]
);
oAuth2Client.setCredentials(token);
return oAuth2Client;
}
async function print(DOC_ID) {
const auth = await authorize();
const docs = google.docs({ version: "v1", auth });
let d = await docs.documents.get({
documentId: DOC_ID,
});
console.log("========", d.data);
}
print(config.get("google.doc_id"));
Run node src/read.js
and you can get contents of your google doc in the terminal.
Conclusion
This is just a basic tutorial to authorize, read and write google docs. You can play around with google doc contents, like convert the contents of google docs into html format and render it.
Reference: https://developers.google.com/gmail/api/quickstart/nodejs
Binod Chaudhary

Software Engineer | Full-Stack Developer