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);
});
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);
});