Skip to content

Instantly share code, notes, and snippets.

@statico
Created March 8, 2019 20:56
Show Gist options
  • Star 2 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save statico/764d8eb7cef3676da1021e25d7f916ea to your computer and use it in GitHub Desktop.
Save statico/764d8eb7cef3676da1021e25d7f916ea to your computer and use it in GitHub Desktop.
Get a Google Sheet using NodeJS async and TypeScript and Service Account credentials
import * as fs from 'fs-extra'
import { google } from 'googleapis'
import * as pathlib from 'path'
const getSheet = async (
keyFile: string,
spreadsheetId: string,
range: string
): Promise<string[][]> => {
const auth = await google.auth.getClient({
keyFile,
scopes: ['https://www.googleapis.com/auth/spreadsheets.readonly']
})
const sheets = google.sheets('v4')
const values: any = await new Promise((resolve, reject) => {
sheets.spreadsheets.values.get(
{
auth,
spreadsheetId,
range
},
(err, data) => {
if (err) {
reject(err)
} else {
resolve(data)
}
}
)
})
return values.data.values
}
export const syncData = async (credentialsPath: string): Promise<void> => {
const dataDir = pathlib.resolve(__dirname, '../data')
await fs.mkdirp(dataDir)
const rows = await getSheet(
credentialsPath,
'xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx',
'Sheet 1!1:9999'
)
console.log('XXX', rows)
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment