NodeJS Request: How do I get `response.statusCode` when piping?
Asked Answered
S

1

6

Sorry guys, I'm kind of lost. How can I console.log response.statusCode when piping?

var express = require('express');
var path = require('path');
var request = require('request');
var fs = require('fs');
var app = express();
var port = 8000;

var destination = fs.createWriteStream('./downloads/google.html');
var url = "http://www.google.com/";
request(url).pipe(destination)
.on("finish", function() {
    console.log("done");
    console.log(response.statusCode); // <<<<<<<<<<<<<<<<<<<<<<<<<<<< this
})
.on("error", function(err){
  console.log(err);
});

app.listen(port, function(){
console.log('running server on ' + port);
});
Seldon answered 23/9, 2017 at 15:56 Comment(0)
C
17

You need to catch the response event from request. It won't be in the finished event from the pipe. You should also consider catching errors before the pipe. This is where you'll catch network errors. After the pipe you'll catch file errors.

request(url)
.on('response', function(response) {
    console.log(response.statusCode) // <--- Here 200
})
.on("error", function(err){
    console.log("Problem reaching URL: ", err);
 })
.pipe(destination)
.on("finish", function(response) {
    console.log("done");
})
.on("error", function(err){
    console.log("Problem writing file: ", err);
});
Chili answered 23/9, 2017 at 16:9 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.