Reputation:
I'm using axios to download image in nodejs. I've added the following the code
const axios = require("axios").default;
const fs = require("fs");
const url =
"https://images.pexels.com/photos/11431628/pexels-photo-11431628.jpeg?auto=compress&cs=tinysrgb&dpr=2&h=750&w=1260";
async function downloadImage() {
try {
const { data } = await axios.get(url);
data.pipe(fs.createWriteStream("sample.jpg"));
} catch (error) {
console.log(error);
}
}
downloadImage();
But I get the following error
TypeError: data.pipe is not a function
Upvotes: 5
Views: 11194
Reputation: 2098
.pipe()
can only be used on streams. To get axios response in streams, add a config object with responseType:'stream'
const { data } = await axios.get(url, { responseType: "stream" });
data.pipe(fs.createWriteStream("sample.jpg"));
You can also use got.
got has a stream method and you can directly pipe into a writable stream.
got.stream(url).pipe(fs.createWriteStream("sample.jpg"))
Upvotes: 11
Reputation: 2332
in your code axios does not return a stream . pipe can only used with in stream
const { data } = await axios.get('https://stream.example.com', {
responseType: 'stream'
});
use this way then it work fine
Upvotes: 0