Search code examples
javascriptnode.jsnpm-requestnode-streams

How to pipe() npm-request only if HTTP 200 is received?


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!


Solution

  • 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'))
        }
      })