【发布时间】:2023-02-19 14:45:39
【问题描述】:
我有两种方法。
第一个读取文件并将其作为纯文本写入该文件。第二个将文件作为流写入。
为了让它工作,我不得不在 require 中添加 fs 两次。
const fs = require('fs').promises;
const fs2 = require('fs');
我试图了解其中的区别以及为什么我需要两次。但似乎没有 promise 的 fs 没有能力使用 createWriteStream 而没有 .promises 的 fs 没有能力使用 writeFile
/**
* Serializes credentials to a file compatible with GoogleAUth.fromJSON.
*
* @param {OAuth2Client} client
* @return {Promise<void>}
*/
async function saveCredentials(client) {
const content = await 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,
});
await fs.writeFile(TOKEN_PATH, payload);
}
第二个以流的形式写入文件
/**
* Download file
* @param {OAuth2Client} authClient An authorized OAuth2 client.
*/
async function downloadFile(authClient) {
const service = google.drive({version: 'v3', auth: authClient});
const fileStream = fs2.createWriteStream("test.txt")
fileId = FILEID;
try {
const file = await service.files.get({
fileId: fileId,
alt: 'media',
}, {
responseType: "stream"
},
(err, { data }) =>
data
.on('end', () => console.log('onCompleted'))
.on('error', (err) => console.log('onError', err))
.pipe(fileStream)
);
} catch (err) {
// TODO(developer) - Handle error
throw err;
}
}
请注意,这确实有效,我只是想围绕 Node.js 进行思考。
【问题讨论】:
标签: javascript node.js google-api-nodejs-client