Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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);
});
like image 983
Emilio Avatar asked Dec 14 '22 20:12

Emilio


1 Answers

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);
});
like image 97
Mark Avatar answered Dec 21 '22 09:12

Mark