javascript - NodeJS - 从 Google Drive 下载媒体
问题描述
我正在尝试使用 googleapis 库从谷歌驱动器下载一个 idFile。但是我遇到以下错误:
无法读取未定义的属性“数据”
这是我的代码:
const express = require("express");
const path = require ("path");
const bodyParser = require("body-parser");
const ejs = require("ejs");
const app = express();
const port = 2000
// Google getting started section
const fs = require('fs');
const readline = require('readline');
const {google} = require('googleapis');
app.use(express.static(path.join(__dirname, 'public')));
app.listen(port, () => {
// Load client secrets from a local file.
fs.readFile('credentials.json', (err, content) => {
if (err) return console.log('Error loading client secret file:', err);
// Authorize a client with credentials, then call the Google Drive API.
authorize(JSON.parse(content), listFiles, downloadFile);
});
console.log(`Example app listening at http://localhost:${port}`)
})
// If modifying these scopes, delete token.json.
const SCOPES = ['https://www.googleapis.com/auth/drive.readonly',
'https://www.googleapis.com/auth/drive.metadata.readonly',
"https://www.googleapis.com/auth/drive.file"];
// The file token.json stores the user's access and refresh tokens, and is
// created automatically when the authorization flow completes for the first
// time.
const TOKEN_PATH = 'token.json';
/**
* Create an OAuth2 client with the given credentials, and then execute the
* given callback function.
* @param {Object} credentials The authorization client credentials.
* @param {function} callback The callback to call with the authorized client.
*/
async 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]);
// Check if we have previously stored a token.
await fs.readFile(TOKEN_PATH, async (err, token) => {
if (err) return getAccessToken(oAuth2Client, callback);
oAuth2Client.setCredentials(JSON.parse(token));
await callback(oAuth2Client);
});
}
/**
* Get and store new token after prompting for user authorization, and then
* execute the given callback with the authorized OAuth2 client.
* @param {google.auth.OAuth2} oAuth2Client The OAuth2 client to get token for.
* @param {getEventsCallback} callback The callback for the authorized client.
*/
async function getAccessToken(oAuth2Client, callback) {
const authUrl = await 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);
// Store the token to disk for later program executions
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.
*/
async function listFiles(auth) {
const drive = await 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(async (file) => {
await downloadFile(auth);
});
} else {
console.log('No files found.');
}
});
}
// download to local file
async function downloadFile(auth) {
const drive = google.drive({version: "v3", auth});
var fileId = "1l-2thXStT2W57Ovo9IUI5ki1zP7afCZ6"
var dest = await fs.createWriteStream("/public/images/photo.jpg");
drive.files.get(
{fileId: fileId, alt: "media"},
{responseType: "stream"},
async function(err, res) {
res.data
.on("end", () => {
})
.on("error", err => {
console.log("Error", err);
})
.pipe(dest);
// I am geeting success but I cant find the Image
console.log("success");
});
}
我使用以下资源编写了它:
https://medium.com/@humadvii/downloading-files-from-google-drive-using-node-js-3704c142a5f6
但我得到的错误是这个:
(node:13788) UnhandledPromiseRejectionWarning: TypeError: Cannot read property 'data' of undefined at C:\info\nodejs\server spectrum\main.js:123:13 at processTicksAndRejections (internal/process/task_queues.js:95:5) (
node --trace-warnings ...
用于显示警告的创建位置)(节点:13788) UnhandledPromiseRejectionWarning:未处理的承诺拒绝。此错误源于在没有 catch 块的情况下抛出异步函数内部,或拒绝未使用 .catch() 处理的承诺。要在未处理的 Promise 拒绝时终止节点进程,请使用 CLI 标志--unhandled-rejections=strict
(请参阅https://nodejs.org/api/cli.html#cli_unhandled_rejections_mode)。(拒绝 id:2)(节点:13788)[DEP0018] DeprecationWarning:不推荐使用未处理的承诺拒绝。将来,未处理的 Promise 拒绝将使用非零退出代码终止 Node.js 进程。块引用
指向以下代码行:
res.data
.on("end", () => {
})
.on("error", err => {
console.log("Error", err);
})
.pipe(dest);
你知道我该如何解决这个问题吗?非常感谢!!
解决方案
这直接来自文档
var fileId = '0BwwA4oUTeiV1UVNwOHItT0xfa2M';
var dest = fs.createWriteStream('/tmp/photo.jpg');
drive.files.get({
fileId: fileId,
alt: 'media'
})
.on('end', function () {
console.log('Done');
})
.on('error', function (err) {
console.log('Error during download', err);
})
.pipe(dest);
推荐阅读
- driver - 从头开始执行窗口模糊并闪烁:视频驱动程序有故障吗?
- react-admin - 按下 DeleteButton 后出现错误页面
- java - 仅使用 java 中的循环和数组计算 O(n) 中数组中的不同元素
- postgresql - asdf 在哪里安装 postgres
- python - 如何简化这些嵌套的 for 循环?
- vhdl - 当我为函数提供它所期望的子类型参数的父级时会发生什么?
- google-chrome - VS Code 检查元素
- php - 在联系表 7 字段中使用 URL 参数
- javascript - Sequelize - 在 findAll 之后,使用单个查询删除
- c# - gRPC - 在 c# 中没有死锁的许多客户端的过程