I’m creating an Electron application and I want to stream an image to a file (so basically download it).
I want to use the native Fetch API because the request module would be a big overhead.
But there is no pipe method on the response, so I can’t do something like
JavaScript
x
3
1
fetch('https://imageurl.jpg')
2
.then(response => response.pipe(fs.createWriteStream('image.jpg')));
3
So how can I combine fetch
and fs.createWriteStream
?
Advertisement
Answer
I got it working. I made a function which transforms the response into a readable stream.
JavaScript
1
15
15
1
const responseToReadable = response => {
2
const reader = response.body.getReader();
3
const rs = new Readable();
4
rs._read = async () => {
5
const result = await reader.read();
6
if(!result.done){
7
rs.push(Buffer.from(result.value));
8
}else{
9
rs.push(null);
10
return;
11
}
12
};
13
return rs;
14
};
15
So with it, I can do
JavaScript
1
3
1
fetch('https://imageurl.jpg')
2
.then(response => responseToReadable(response).pipe(fs.createWriteStream('image.jpg')));
3