0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 1 year has passed since last update.

GraphAPIを使ってファイルをダウンロードする(Node.js)

Last updated at Posted at 2022-06-10

@microsoft/microsoft-graph-clientを使ってファイルをダウンロードするときにめんどくさかったのでメモ。

const fs = require('fs').promises;
const Blob = require('cross-blob');
const zlib = require('zlib');
const { PassThrough } = require('stream');

async main () => {
  /**
   * 大きいファイル、小さいファイル、テキストファイルなど、ファイルの種類によって返ってくるクラスが変わる
   * @type {PassThrough|Blob|zlib.Gunzip}
   */
  const content = await client.api('/drives/{drive-id}/items/{item-id}/content').get();

  let data;
  if (content instanceof PassThrough) {
    let chunks = [];
    for await (const chunk of content) {
      chunks.push(chunk);
    }
    data = Buffer.concat(chunks);
  } else if (content instanceof Blob) {
    data = Buffer.from(await content.text());
  } else if (content instanceof zlib.Gunzip) {
    data = await new Promise((resolve, reject) => {
      let chunks = [];
      content
        .on('data', (chunk) => chunks.push(chunk))
        .on('error', reject)
        .on('end', () => {
          resolve(Buffer.concat(chunks));
        });
    });
  } else {
    throw new Error(`Unrecognize type of the content. '${content.constructor.name}'.`);
  }
  await fs.writeFile('filename', data);
}
0
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?