Last active
November 9, 2024 17:18
-
-
Save tomlarkworthy/de4d2d45474c47b8faac523709017eb3 to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// 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)}`); | |
} |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
{ | |
"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" | |
} | |
} |
@tomlarkworthy Cool! Do you know of any way to get the document as HTML or even markdown? I read through the docs but I can't find an option for formatting
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
No need to read the service account key json file manually. You can specify its path in the
GOOGLE_APPLICATION_CREDENTIALS
environment variable, orkeyFile
property, as explained here: https://googleapis.dev/nodejs/googleapis/latest/sheets/index.html#service-account-credentials