NodeJS请求:如何在管道时获得`response.statusCode`?

时间:2017-09-23 15:56:56

标签: node.js express node-request

对不起,伙计们,我有点迷路了。如何在管道时使用console.log response.statusCode

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

1 个答案:

答案 0 :(得分:5)

您需要从response抓住request事件。它不会出现在管道的finished事件中。您还应该考虑在管道之前捕获错误。这是您将捕获网络错误的地方。在管道之后你会发现文件错误。

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