问题
request.get(fileLink)
.on('response', function(response) {
if (response.statusCode == 200 && response.headers['content-type'] == 'application/vnd.ms-excel') {
return true;
} else {
return false;
}
})
.pipe(fs.createWriteStream('data.xls'));
I need to save file if response code is 200 and content-type is application/vnd.ms-excel. How to organize code?
回答1:
The way to do it, is to pipe response
if the condition is met, and destroy the response
stream otherwise.
request.get(fileLink)
.on('response', function(response) {
if (response.statusCode == 200 && response.headers['content-type'] == 'application/vnd.ms-excel') {
return response
.pipe(fs.createWriteStream('data.xls'))
.on('error', console.error)
}
response.destroy();
});
来源:https://stackoverflow.com/questions/51407928/pipe-after-successful-condition-node-js