Skip to content

Instantly share code, notes, and snippets.

@tomlarkworthy
Last active July 3, 2023 10:13
Show Gist options
  • Save tomlarkworthy/de4d2d45474c47b8faac523709017eb3 to your computer and use it in GitHub Desktop.
Save tomlarkworthy/de4d2d45474c47b8faac523709017eb3 to your computer and use it in GitHub Desktop.
// 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"
}
}
@pejalo
Copy link

pejalo commented Jul 3, 2023

No need to read the service account key json file manually. You can specify its path in the GOOGLE_APPLICATION_CREDENTIALS environment variable, or keyFile property, as explained here: https://googleapis.dev/nodejs/googleapis/latest/sheets/index.html#service-account-credentials

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment