Created
May 28, 2020 12:16
-
-
Save sandiprb/189ec36a749239fba4866229cbf9c9e5 to your computer and use it in GitHub Desktop.
Node JS script to fetch Google Sheets data as json
This file contains 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
const { GoogleSpreadsheet } = require('google-spreadsheet'); | |
const fs = require('fs'); | |
const JSON_FILE_NAME = 'data.json' | |
const FILE_PATH = `/data/${JSON_FILE_NAME}` | |
const GOOGLE_SHEET_ID = '' | |
/* Create google credentials and save the credentials json file */ | |
const creds = require('./credentials.json') | |
function writeJsonFile(data) { | |
fs.writeFile(FILE_PATH, JSON.stringify(data, null, 4), (err) => { | |
if (err) throw err; | |
console.log('Completed!!'); | |
console.log(`Data saved in ${FILE_PATH} file`); | |
}); | |
} | |
async function fetchData() { | |
console.log('Loading data form spreadsheet..') | |
const doc = new GoogleSpreadsheet(GOOGLE_SHEET_ID) | |
await doc.useServiceAccountAuth(creds) | |
await doc.loadInfo() | |
console.log('File loaded, reading sheet rows') | |
const sheet = doc.sheetsByIndex[0] | |
const rows = await sheet.getRows() | |
const data = rows.map((row, index) => ({...row}) | |
console.log(`Data loaded, generating ${JSON_FILE_NAME} file`) | |
writeJsonFile(data) | |
} | |
fetchData() |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment