Pipe after successful condition Node js [duplicate]

不问归期 提交于 2019-12-13 18:14:22

问题


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!