Skip to content

Instantly share code, notes, and snippets.

@tomlarkworthy
Last active Mar 22, 2020
Embed
What would you like to do?
// Example in Typescript, nodejs reads a Google Doc if the service account is added as a viewer
// No manual OAUTH2 approval steps required. Just use the google share settings to share
// Use the client_email address found in the crendentials file as the
import fs = require('fs');
import {JWT, auth} from 'google-auth-library';
import {google} from 'googleapis';
const SCOPES = [
// Other options at https://developers.google.com/identity/protocols/oauth2/scopes#docsv1
'https://www.googleapis.com/auth/documents.readonly'
];
// Service account key, see https://cloud.google.com/iam/docs/creating-managing-service-account-keys#creating_service_account_keys
// If you deploy to GCF, Cloud Run you may be able to pick up credentials from the environment and not need a file
fs.readFile('creds/assisty.json', (err, crendentials) => {
if (err) return console.log('Error loading service credentials:', err);
const client = <JWT> auth.fromJSON(JSON.parse(crendentials.toString()));
client.scopes = SCOPES;
run(client);
});
async function run(auth: JWT) {
// https://developers.google.com/docs/api/reference/rest
const docs = google.docs({
version: 'v1',
auth
});
const doc = await docs.documents.get({
documentId: '18uEHALOrqvh9Nf4yosKPZDdeKZV6nfk8Ddd4cEXjgfA',
});
console.log(`${JSON.stringify(doc.data.body)}`);
}
{
"name": "Google Doc reading example",
"version": "1.0.0",
"description": "A simple Node.js command-line application that reads a doc through the Docs API.",
"dependencies": {
"google-auth-library": "^5.10.1",
"googleapis": "^48.0.0"
},
"devDependencies": {
"@types/node": "^13.9.2",
"typescript": "^3.8.3"
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment