javascript - 从谷歌驱动程序自行下载 xlsx 文件
问题描述
因此,我正在尝试制作一个小脚本,该脚本将使用 google drive API 下载一个确定的 excel 文件,通过遵循 google API 教程,我遇到了两个错误“无法读取未定义的属性”和“请求的转换是不支持”这里是代码:
const fs = require('fs');
const readline = require('readline');
const {google} = require('googleapis');
const SCOPES = ['https://www.googleapis.com/auth/drive'];
const TOKEN_PATH = 'token.json';
fs.readFile('credentials.json', (err, content) => {
if (err) return console.log('Error loading client secret file:', err);
authorize(JSON.parse(content), listFiles);
});
/**
* @param {Object} credentials The authorization client credentials.
* @param {function} callback The callback to call with the authorized client.
*/
function authorize(credentials, callback) {
const {client_secret, client_id, redirect_uris} = credentials.installed;
const oAuth2Client = new google.auth.OAuth2(
client_id, client_secret, redirect_uris[0]);
fs.readFile(TOKEN_PATH, (err, token) => {
if (err) return getAccessToken(oAuth2Client, callback);
oAuth2Client.setCredentials(JSON.parse(token));
callback(oAuth2Client);
});
}
/**
* @param {google.auth.OAuth2} oAuth2Client The OAuth2 client to get token for.
* @param {getEventsCallback} callback The callback for the authorized client.
*/
function getAccessToken(oAuth2Client, callback) {
const authUrl = oAuth2Client.generateAuthUrl({
access_type: 'offline',
scope: SCOPES,
});
console.log('Authorize this app by visiting this url:', authUrl);
const rl = readline.createInterface({
input: process.stdin,
output: process.stdout,
});
rl.question('Enter the code from that page here: ', (code) => {
rl.close();
oAuth2Client.getToken(code, (err, token) => {
if (err) return console.error('Error retrieving access token', err);
oAuth2Client.setCredentials(token);
fs.writeFile(TOKEN_PATH, JSON.stringify(token), (err) => {
if (err) return console.error(err);
console.log('Token stored to', TOKEN_PATH);
});
callback(oAuth2Client);
});
});
}
/**
* Lists the names and IDs of up to 10 files.
* @param {google.auth.OAuth2} auth An authorized OAuth2 client.
*/
function listFiles(auth) {
const drive = google.drive({version: 'v3', auth});
drive.files.list({
pageSize: 10,
fields: 'nextPageToken, files(id, name)',
}, (err, res) => {
if (err) return console.log('The API returned an error: ' + err);
const files = res.data.files;
if (files.length) {
console.log('Files:');
files.map((file) => {
console.log(`${file.name} (${file.id})`);
});
} else {
console.log('No files found.');
}
var fileId = '1lKhyW1O519_1V1QhL9Vkbu55HqyfrgaUbnF4fmhZqU0';
var dest = fs.createWriteStream('/home/oem/Desktop/TTHIS/report-2019-03-26.xls');
drive.files.export({
fileId: fileId,
mimeType: 'xls'
})
.on('end', function () {
console.log('Done');
})
.on('error', function (err) {
console.log('Error during download', err);
})
.pipe(dest);
});
}
记住代码的第一部分只是为了授权,所以真正的问题从函数 listFiles() 开始。感谢您的时间!
解决方案
这个改装怎么样?
修改点:
- 为了使用
response.data
,{responseType: 'stream'}
使用。- 该线程可能对您的情况有用。
- 在线程中,使用了files.get的方法。但这也可以用于files.export的方法。
- 没有 mimeType
xls
。请使用application/vnd.openxmlformats-officedocument.spreadsheetml.sheet
xlsx 格式的 mimeType。
修改后的脚本:
请进行如下修改。
从:var fileId = '1lKhyW1O519_1V1QhL9Vkbu55HqyfrgaUbnF4fmhZqU0';
var dest = fs.createWriteStream('/home/oem/Desktop/TTHIS/report-2019-03-26.xls');
drive.files.export({
fileId: fileId,
mimeType: 'xls'
})
.on('end', function () {
console.log('Done');
})
.on('error', function (err) {
console.log('Error during download', err);
})
.pipe(dest);
至:
var fileId = '1lKhyW1O519_1V1QhL9Vkbu55HqyfrgaUbnF4fmhZqU0';
var dest = fs.createWriteStream('/home/oem/Desktop/TTHIS/report-2019-03-26.xls');
drive.files.export({
fileId: fileId,
mimeType: 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet',
}, {responseType: 'stream'}, function(err, response) {
response.data
.on('end', function() {
console.log("Done.");
})
.on('error', function(err) {
console.log('Error during download', err);
return process.exit();
})
.pipe(dest);
});
笔记:
- 如果出现 Drive API 相关的错误,请再次在 API 控制台确认 Drive API 是否启用。
- 这个修改后的脚本假设文件
1lKhyW1O519_1V1QhL9Vkbu55HqyfrgaUbnF4fmhZqU0
是电子表格。
在我的环境中,我可以确认这个修改后的脚本有效。但是,如果这对您的环境不起作用,我深表歉意。
推荐阅读
- java - 使用 PDFBox 填写表单时如何替换缺少的字体?
- javascript - 找出哪个关闭按钮关闭了警报框
- traefik - Traefik ReplacePathRegex 没有正确路由
- php - MYSQLdump 不能在 where 子句中使用 SELECT 语句
- java - Apache Storm 可靠性:确认/失败具有更改值的元组会保证可靠性吗?
- python - 试图在python中下载图像但它不起作用
- c# - ASP.NET Core - 添加控制器时出现“找不到方法”错误
- swift - Codable : 不符合协议'Decodable'
- angular - 角度 HttpClient get 方法不调用服务器
- java - Java流按2个字段排序