2

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!

rtn
  • 127,556
  • 20
  • 111
  • 121
Mikser
  • 929
  • 10
  • 16

1 Answers1

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'))
    }
  })
rtn
  • 127,556
  • 20
  • 111
  • 121
  • How come this doesn't work? `const req = request.get('http://thewalter.net/stef/software/rtfx/sample.rtf', (error, response, body) => { if(response.statusCode === 200) { req.pipe(fs.createWriteStream(__dirname + '/testDoc.rtf')); } });` – Mikser Mar 14 '18 at 14:03
  • no errors, but if the response is 200 then the file that is saved is empty – Mikser Mar 14 '18 at 14:06
  • 1
    I guess the request stream gets closed by the time this `(err,res,body) => {}` handler is executed – Mikser Mar 14 '18 at 15:03
  • Probably yep. Is the `body` a `Buffer` with the response? – rtn Mar 14 '18 at 15:30