Skip to content

Instantly share code, notes, and snippets.

@bhouston
Last active December 12, 2023 18:42
Show Gist options
  • Save bhouston/20a65e44510aee145383e762c0dfeb48 to your computer and use it in GitHub Desktop.
Save bhouston/20a65e44510aee145383e762c0dfeb48 to your computer and use it in GitHub Desktop.
Save remote image to disk
import axios from 'axios';
import fs from 'fs';
import path from 'path';
async function downloadImageAsAxiosStream(url: string, filename: string) {
// Fetch the image
const response = await axios({
url,
method: 'GET',
responseType: 'stream'
});
const contentType = response.headers['content-type'];
const extension = contentType?.split('/')[1];
const writer = fs.createWriteStream(filename + '.' + extension);
response.data.pipe(writer);
return new Promise((resolve, reject) => {
writer.on('finish', () => {
writer.close();
resolve(null);
});
writer.on('error', () => {
writer.close();
reject(null);
});
});
}
async function downloadImageAsAxiosArrayBuffer(url: string, filename: string) {
// Fetch the image
const response = await axios({
url,
method: 'GET',
responseType: 'arraybuffer'
});
const contentType = response.headers['content-type'];
const extension = contentType?.split('/')[1];
fs.writeFileSync(filename + '.' + extension, Buffer.from(response.data));
}
async function downloadImageAsFetchArrayBuffer(url: string, filename: string) {
// Fetch the image
const response = await fetch(url);
const contentType = response.headers.get('content-type');
const extension = contentType?.split('/')[1];
fs.writeFileSync(
filename + '.' + extension,
Buffer.from(await response.arrayBuffer())
);
}
async function main() {
const fluidImageUrl =
'https://configure-imagecomposer.fluidretail.net/recipe/13385468/image/Front,1.jpg';
const threekitImageUrl = `https://lv-api.3kit.com/api/configurations/TVY8ABEK/image/Front`;
await downloadImageAsAxiosStream(fluidImageUrl, 'fluid-Front-stream');
await downloadImageAsAxiosStream(threekitImageUrl, 'threekit-Front-stream');
await downloadImageAsAxiosArrayBuffer(
fluidImageUrl,
'fluid-Front-arraybuffer'
);
await downloadImageAsAxiosArrayBuffer(
threekitImageUrl,
'threekit-Front-arraybuffer'
);
await downloadImageAsFetchArrayBuffer(fluidImageUrl, 'fluid-Front-fetch');
await downloadImageAsFetchArrayBuffer(
threekitImageUrl,
'threekit-Front-fetch'
);
}
main();
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment