I'm downloading a file from remote server using axios post method,then saving to the disk. Once the file is saved to disk I need to send it to client in response.
let response = await axios.post(url, body, {headers :headers, responseType:'stream'})
let filePath = "reports/" + response.headers['content-disposition'].split("filename=")[1].replace(/\"/g, "");
await response.data.pipe(fs.createWriteStream(filePath))
res.download(filePath);
The problem I'm facing is, Response is sent when the file writing is still in progress. If there is any alternative, Please suggest.
EDIT:- The problem was with the write stream.
Solution:-
let response = await axios.post(url, body, {headers :headers, responseType:'stream'});
let filePath = "reports/" + response.headers['content-disposition'].split("filename=")[1].replace(/\"/g, "");
let ws = fs.createWriteStream(filePath);
new Promise((resolve, reject) => {
ws.on('open', () => {
response.data.pipe(ws);
}).on('error', function (err) {
reject(res.send({error: "message"}));
}).on('finish', function () {
ws.end();
resolve(res.download(filePath));
});
});
Link:- fs.createWriteStream does not immediately create file?