admin管理员组

文章数量:1429061

I have the following code:

let request = require('request');
let fs = require('fs');

request.get('http://localhost:8080/report.rtf')
  .pipe(fs.createWriteStream(__dirname + '/savedDoc.rtf'));

It works well, but only if the document is successfully downloaded from the given URL. However, if there is any HTTP: 403, 404 or any other error, an empty file is saved with zero length!

How can I .pipe() this only in case of HTTP: 200 response without using any additional HEAD requests? It should be possible to do in one go!

I have the following code:

let request = require('request');
let fs = require('fs');

request.get('http://localhost:8080/report.rtf')
  .pipe(fs.createWriteStream(__dirname + '/savedDoc.rtf'));

It works well, but only if the document is successfully downloaded from the given URL. However, if there is any HTTP: 403, 404 or any other error, an empty file is saved with zero length!

How can I .pipe() this only in case of HTTP: 200 response without using any additional HEAD requests? It should be possible to do in one go!

Share Improve this question edited Mar 14, 2018 at 12:40 ralphtheninja 134k20 gold badges113 silver badges122 bronze badges asked Mar 14, 2018 at 12:27 MikserMikser 99910 silver badges16 bronze badges
Add a ment  | 

1 Answer 1

Reset to default 7

Check .statusCode before piping:

const req = request
  .get('http://localhost:8080/report.rtf')
  .on('response', function (res) {
    if (res.statusCode === 200) {
      req.pipe(fs.createWriteStream(__dirname + '/savedDoc.rtf'))
    }
  })

本文标签: javascriptHow to pipe() npmrequest only if HTTP 200 is receivedStack Overflow