条件条件成功后管道

时间:2018-07-18 17:32:35

标签: javascript node.js conditional-statements

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'));

如果响应代码为200并且content-type为application / vnd.ms-excel,则需要保存文件。如何组织代码?

1 个答案:

答案 0 :(得分:0)

方法是:如果满足条件,则用管道输送response,否则销毁response流。

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();
    });