簡記:Node.js使用google sheet API讀取(新版google-auth&typescript)
這裡是serviceaccount的json放在環境變數中,並googleapis套件操作google sheet api。
因為新版google auth套件有改版把fromJSON()和給廢掉,導致升級版本程式要調整,跟google&AI弄了弄,範例都給我奇怪的結果,這篇把這些整理起來
pnpm add googleapis
import { google, sheets_v4 } from 'googleapis';
async function main(...args: string[]) {
const credentials = JSON.parse(process.env.SHEET_CREDENTIALS);
const authClient = new google.auth.JWT({
scopes: ['https://www.googleapis.com/auth/spreadsheets']
})
authClient.fromJSON(credentials);
const sheetAPIs = google.sheets({ version: 'v4', auth: authClient });
const res = await sheetAPIs.spreadsheets.get({
spreadsheetId: process.env.SHEET_ID
});
if (!res.ok) throw Error(`http error code:${res.status}`);
console.log(res.data)
}
const args = process.argv.slice(2);
main(...args).catch(console.error);
scopes上面是提供讀寫
如果只讀取,就改成 scopes: ['https://www.googleapis.com/auth/spreadsheets.readonly']
留言