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.

await を使わず node-fetch をつかって、画像をダウンロードして Base64 Data URI として取得する方法

Posted at

概要

await を使わずに、node-fetch をつかって、画像をダウンロードして Base64 Data URI として取得する方法  です。

(async ついてない関数内でやらないといけないシチュエーションにて)

環境

  • ES6~
  • Node.js v14~
  • node-fetch v2~

コード例

import fetch from "node-fetch";

const url = 'https://example.com/something.jpg';

fetch(url)
    .then(response => {
        return new Promise((resolve, reject) => {
            if (!response.ok) {
                // - サーバーエラーが発生
                reject(new Error(`Server Error, status:${response.status} statusText:${response.statusText}`));
            }
            const contentType = response.headers.get('content-type');
            response.arrayBuffer().then(data => {
                resolve({contentType, buffer: Buffer.from(data)});
            }).catch(reject);
        });
    })
    .then(data => {
        const {contentType, buffer} = data;
        const base64str = buffer.toString('base64');
        return `data:${contentType};base64,${base64str}`
    })
    .then(dataURI => {
        console.log(dataURI);
    })
    .catch(error => {
        // エラーのハンドリングをする
        console.log(`Error occurred`, error);
    });


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?