インターネット上にある画像の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));
以上です。