You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何在Node.js中实现非异步的Google Sheets API v4服务构建?

Google Sheets API v4 从Python迁移至Node.js的异步适配问题

我正在将部分Python代码迁移到Node.js。在Python中,我通过self.service = BuildService().build('sheets')同步建立Google Sheets API v4连接,可随时初始化该连接并直接调用接口获取结果。

迁移到Node.js时遇到了核心问题:Google官方快速入门示例使用异步函数,虽然能正常运行,但无法像Python那样直接获取函数返回值——尝试用全局变量获取服务实例或接口结果,得到的始终是Promise对象;使用await则必须包裹在异步函数内,结果无法跳出函数作用域。

代码流程对比

Python 同步实现

service = BuildService().build('sheets')
key = 'xxxxxxxx'
ranges = ['test!A1']

res = service.spreadsheets().values().get(spreadsheetId=key, range=ranges).execute()

Node.js 异步困境

var sheets  = authorize() // 返回的是Promise对象,而非直接的服务实例
var id = 'xxxxxxx'
ranges = ['test!A1']

const res = sheets.spreadsheets.values.batchGet({
  spreadsheetId: id, 
  ranges: ranges_ar, valueRenderOption: "FORMATTED_VALUE"}
)
// res 是Pending状态的Promise,无法直接获取结果
// Promise {[[PromiseState]]: 'pending', [[PromiseResult]]: undefined, Symbol(async_id_symbol): 16, Symbol(trigger_async_id_symbol): 1}

我使用authorize().then(listMajors).catch(console.error);的方式能正常执行接口调用,但无法将listMajors内的结果带出函数;尝试过各种包装方式,均未解决问题。

尝试的完整脚本(未运行成功)

基于相关建议修改的脚本,但尚未能正常工作:

// Google Sheets API Node.js快速入门基础框架
const fs = require('fs');
const path = require('path');
const process = require('process');
const {authenticate} = require('@google-cloud/local-auth');
const {google} = require('googleapis');
const request = require("sync-request");

const SCOPES = ['https://www.googleapis.com/auth/spreadsheets'];
const CREDENTIALS_PATH = 'xxxxxx'
const TOKEN_PATH = 'xxxxxxxx';

function loadSavedCredentialsIfExist() {
  try {
    const content = fs.readFile(TOKEN_PATH);
    const credentials = JSON.parse(content);
    return google.auth.fromJSON(credentials);
  } catch (err) {
    return null;
  }
}

function saveCredentials(client) {
  const content = fs.readFile(CREDENTIALS_PATH);
  const keys = JSON.parse(content);
  const key = keys.installed || keys.web;
  const payload = JSON.stringify({
    type: 'authorized_user',
    client_id: key.client_id,
    client_secret: key.client_secret,
    refresh_token: client.credentials.refresh_token,
  });
  fs.writeFile(TOKEN_PATH, payload);
}

function authorize() {
  let client = loadSavedCredentialsIfExist();
  if (client) {
  
  } else{
    client = authenticate({
      scopes: SCOPES,
      keyfilePath: CREDENTIALS_PATH,
    });
    if (client.credentials) {
      saveCredentials(client);
    }
  }

  const sheets = google.sheets({version: 'v4', client});
  return sheets
}

var sheets  = authorize()
var id = 'xxxxxxx'
var ranges= ['Data!A2:E10']

const accessToken = sheets.context._options.auth.credentials.access_token;
const query = new URLSearchParams({ ranges, valueRenderOption: "FORMATTED_VALUE" }).toString();
const url = `https://sheets.googleapis.com/v4/spreadsheets/${id}/values:batchGet?${query}`;
const resObj = request("GET", url, { headers: { Authorization: `Bearer ${accessToken}` }});
const res = resObj.getBody("utf8");
console.log(res);

核心疑问

  • 是否可以不使用异步方式连接Google API V4?
  • 能否沿用Python的同步代码流程改写Node.js代码?
  • 还是迁移到Node.js必须重构全部代码为异步模式?

内容的提问来源于stack exchange,提问作者jason

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.05 07:46:31