0
0

【Node.js】インターネット上にある画像のURLを指定してローカルに画像を保存する

Posted at

インターネット上にある画像のURLを指定してローカルに画像を保存する方法です。

私の環境

  • macOS Ventura
  • Node.js: v20.0.0
  • 開発環境: VSCode

最初に

HTTPリクエストを行うためのライブラリ axios をインストールします。

$ npm init
$ npm install axios

コード

index.js
const fs = require('fs');
const axios = require('axios');

async function downloadImage(url, filePath) {
    try {
        const response = await axios({
            url,
            method: 'GET',
            responseType: 'stream'
        });

        const writer = fs.createWriteStream(filePath);

        response.data.pipe(writer);

        return new Promise((resolve, reject) => {
            writer.on('finish', resolve);
            writer.on('error', reject);
        });
    } catch (error) {
        console.error('Error downloading the image:', error);
    }
}

const imageURL = 'ここに画像のURLを入力';
const localPath = '保存したいローカルパス/image.jpg';

downloadImage(imageURL, localPath)
    .then(() => console.log('Download completed'))
    .catch(error => console.error('Error in download:', 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