Writing the stream returned by node-fetch
I figured it out. the writeable stream will automatically close when the readable does. so I can hook onto that instead:
fetch(url).then(res => new Promise((resolve, reject) => {
const dest = fs.createWriteStream(fn);
res.body.pipe(dest);
dest.on('close', () => resolve());
dest.on('error', reject);
}));
As far as I can tell, your code is correct. I ran
const fs = require("fs");
const fetch = require("node-fetch");
fetch("https://assets-cdn.github.com/images/modules/logos_page/Octocat.png")
.then(
res =>
new Promise((resolve, reject) => {
const dest = fs.createWriteStream("./tmp.txt");
res.body.pipe(dest);
res.body.on("end", () => resolve("it worked"));
dest.on("error", reject);
})
)
.then(x => console.log(x));
and it worked exactly as expected and printed "it worked"