LearnYouNode:回调保持Err的回归真实

时间:2014-10-08 02:48:41

标签: javascript node.js http-get

这是关于LearnYouNode的Node.js课程 这个挑战是:Juggling Async

这是我的代码:

var http = require('http')
var concat = require('concat-stream')
var urlHolder = [];

/*
function printResults()
{
    for(var i = 0; i < 3; i++)
        console.log(urlHolder[i]);
    return;
}*/

function getURL(index) {
    http.get(process.argv[2], function(err, response) {
        if(err)
            return console.error(err);
/*
        response.pipe(concat(function (err, data) {
            if(err)
                return console.error(index);
            urlHolder.push(data.toString());

            if(index === 4)
            {
                printResults();
            }

        }))*/

    })

}
getURL(9)  //The 9 I'm putting as the parameter is random. It is just to pass to the function

/*
for(var index = 2; index < 5; index++){
    getURL(index);
}*/

以下是我输入命令行的内容: node juggleAsync.js http://www.google.com

我已经评论了大块的代码,试图调试它为什么返回err为true。起初,我认为这与我在命令行给出的参数上调用getURL的循环有关。

即使在评论出来之后,我仍然是错误的。我也尝试过不同的网站作为参数 - nada。希望有人可以帮我调试这段代码的精炼版本。

任何帮助将不胜感激。谢谢!

此外,因为我已经包含以下错误。这是非常长的,我不知道包括什么,不包括。我所理解的是,这就是吐出的东西。它超出了人物限制,所以我排出了一半身体。

node juggleAsync.js http://www.google.com 
{ _readableState: 
   { highWaterMark: 16384,
     buffer: [],
     length: 0,
     pipes: null,
     pipesCount: 0,
     flowing: false,
     ended: false,
     endEmitted: false,
     reading: false,
     calledRead: false,
     sync: true,
     needReadable: false,
     emittedReadable: false,
     readableListening: false,
     objectMode: false,
     defaultEncoding: 'utf8',
     ranOut: false,
     awaitDrain: 0,
     readingMore: false,
     decoder: null,
     encoding: null },
  readable: true,
  domain: null,
  _events: { end: [Function: responseOnEnd] },
  _maxListeners: 10,
  socket: 
   { _connecting: false,
     _handle: 
      { fd: 14,
        writeQueueSize: 0,
        owner: [Circular],
        onread: [Function: onread],
        reading: true },
     _readableState: 
      { highWaterMark: 16384,
        buffer: [],
        length: 0,
        pipes: null,
        pipesCount: 0,
        flowing: false,
        ended: false,
        endEmitted: false,
        reading: true,
        calledRead: true,
        sync: false,
        needReadable: true,
        emittedReadable: false,
        readableListening: false,
        objectMode: false,
        defaultEncoding: 'utf8',
        ranOut: false,
        awaitDrain: 0,
        readingMore: false,
        decoder: null,
        encoding: null },
     readable: true,
     domain: null,
     _events: 
      { end: [Object],
        finish: [Function: onSocketFinish],
        _socketEnd: [Function: onSocketEnd],
        free: [Function],
        close: [Object],
        agentRemove: [Function],
        drain: [Function: ondrain],
        error: [Function: socketErrorListener] },
     _maxListeners: 10,
     _writableState: 
      { highWaterMark: 16384,
        objectMode: false,
        needDrain: false,
        ending: false,
        ended: false,
        finished: false,
        decodeStrings: false,
        defaultEncoding: 'utf8',
        length: 0,
        writing: false,
        sync: false,
        bufferProcessing: false,
        onwrite: [Function],
        writecb: null,
        writelen: 0,
        buffer: [],
        errorEmitted: false },
     writable: true,
     allowHalfOpen: false,
     onend: [Function: socketOnEnd],
     destroyed: false,
     bytesRead: 1374,
     _bytesDispatched: 64,
     _pendingData: null,
     _pendingEncoding: '',
     parser: 
      { _headers: [],
        _url: '',
        onHeaders: [Function: parserOnHeaders],
        onHeadersComplete: [Function: parserOnHeadersComplete],
        onBody: [Function: parserOnBody],
        onMessageComplete: [Function: parserOnMessageComplete],
        socket: [Circular],
        incoming: [Circular],
        maxHeaderPairs: 2000,
        onIncoming: [Function: parserOnIncomingClient] },
     _httpMessage: 
      { domain: null,
        _events: {},
        _maxListeners: 10,
        output: [],
        outputEncodings: [],
        writable: true,
        _last: true,
        chunkedEncoding: false,
        shouldKeepAlive: true,
        useChunkedEncodingByDefault: false,
        sendDate: false,
        _headerSent: true,
        _header: 'GET / HTTP/1.1\r\nHost: www.google.com\r\nConnection: keep-alive\r\n\r\n',
        _hasBody: true,
        _trailer: '',
        finished: true,
        _hangupClose: false,
        socket: [Circular],
        connection: [Circular],
        agent: [Object],
        socketPath: undefined,
        method: 'GET',
        path: '/',
        _headers: [Object],
        _headerNames: [Object],
        parser: [Object],
        res: [Circular] },
     ondata: [Function: socketOnData] },
  connection: 
   { _connecting: false,
     _handle: 
      { fd: 14,
        writeQueueSize: 0,
        owner: [Circular],
        onread: [Function: onread],
        reading: true },
     _readableState: 
      { highWaterMark: 16384,
        buffer: [],
        length: 0,
        pipes: null,
        pipesCount: 0,
        flowing: false,
        ended: false,
        endEmitted: false,
        reading: true,
        calledRead: true,
        sync: false,
        needReadable: true,
        emittedReadable: false,
        readableListening: false,
        objectMode: false,
        defaultEncoding: 'utf8',
        ranOut: false,
        awaitDrain: 0,
        readingMore: false,
        decoder: null,
        encoding: null },
     readable: true,
     domain: null,
     _events: 
      { end: [Object],
        finish: [Function: onSocketFinish],
        _socketEnd: [Function: onSocketEnd],
        free: [Function],
        close: [Object],
        agentRemove: [Function],
        drain: [Function: ondrain],
        error: [Function: socketErrorListener] },
     _maxListeners: 10,
     _writableState: 
      { highWaterMark: 16384,
        objectMode: false,
        needDrain: false,
        ending: false,
        ended: false,
        finished: false,
        decodeStrings: false,
        defaultEncoding: 'utf8',
        length: 0,
        writing: false,
        sync: false,
        bufferProcessing: false,
        onwrite: [Function],
        writecb: null,
        writelen: 0,
        buffer: [],
        errorEmitted: false },
     writable: true,
     allowHalfOpen: false,
     onend: [Function: socketOnEnd],
     destroyed: false,
     bytesRead: 1374,
     _bytesDispatched: 64,
     _pendingData: null,
     _pendingEncoding: '',
     parser: 
      { _headers: [],
        _url: '',
        onHeaders: [Function: parserOnHeaders],
        onHeadersComplete: [Function: parserOnHeadersComplete],
        onBody: [Function: parserOnBody],
        onMessageComplete: [Function: parserOnMessageComplete],
        socket: [Circular],
        incoming: [Circular],
        maxHeaderPairs: 2000,
        onIncoming: [Function: parserOnIncomingClient] },
     _httpMessage: 
      { domain: null,
        _events: {},
        _maxListeners: 10,
        output: [],
        outputEncodings: [],
        writable: true,
        _last: true,
        chunkedEncoding: false,
        shouldKeepAlive: true,
        useChunkedEncodingByDefault: false,
        sendDate: false,
        _headerSent: true,
        _header: 'GET / HTTP/1.1\r\nHost: www.google.com\r\nConnection: keep-alive\r\n\r\n',
        _hasBody: true,
        _trailer: '',
        finished: true,
        _hangupClose: false,
        socket: [Circular],
        connection: [Circular],
        agent: [Object],
        socketPath: undefined,
        method: 'GET',
        path: '/',
        _headers: [Object],
        _headerNames: [Object],
        parser: [Object],
        res: [Circular] },
     ondata: [Function: socketOnData] },
  httpVersion: '1.1',
  complete: false,
  headers: 
   { date: 'Wed, 08 Oct 2014 02:57:46 GMT',
     expires: '-1',
     'cache-control': 'private, max-age=0',
     'content-type': 'text/html; charset=ISO-8859-1',
     'set-cookie': 
      [ 'PREF=ID=2d36a12041e95f4c:FF=0:TM=1412737066:LM=1412737066:S=DS6oLzPxyoZ6NZou; expires=Fri, 07-Oct-2016 02:57:46 GMT; path=/; domain=.google.com',
        'NID=67=qj_qQhWU6YsBPYxf1szOnSENrlW_v27SkcoLTwXh-cRWB3MOtSfYX_v-ldvLCS06x4iMQ-7SJBTFhIMb8yR7lTso8dqAsvub0NJyZghv_xzpRI9YT0_c6rkSM_NmjeTG; expires=Thu, 09-Apr-2015 02:57:46 GMT; path=/; domain=.google.com; HttpOnly' ],
     p3p: 'CP="This is not a P3P policy! See http://www.google.com/support/accounts/bin/answer.py?hl=en&answer=151657 for more info."',
     server: 'gws',
     'x-xss-protection': '1; mode=block',
     'x-frame-options': 'SAMEORIGIN',
     'alternate-protocol': '80:quic,p=0.01',
     'transfer-encoding': 'chunked' },
  trailers: {},
  _pendings: [],
  _pendingIndex: 0,
  url: '',
  method: null,
  statusCode: 200,
  client: 
   { _connecting: false,
     _handle: 
      { fd: 14,
        writeQueueSize: 0,
        owner: [Circular],
        onread: [Function: onread],
        reading: true },
     _readableState: 
      { highWaterMark: 16384,
        buffer: [],
        length: 0,
        pipes: null,
        pipesCount: 0,
        flowing: false,
        ended: false,
        endEmitted: false,
        reading: true,
        calledRead: true,
        sync: false,
        needReadable: true,
        emittedReadable: false,
        readableListening: false,
        objectMode: false,
        defaultEncoding: 'utf8',
        ranOut: false,
        awaitDrain: 0,
        readingMore: false,
        decoder: null,
        encoding: null },
     readable: true,
     domain: null,
     _events: 
      { end: [Object],
        finish: [Function: onSocketFinish],
        _socketEnd: [Function: onSocketEnd],
        free: [Function],
        close: [Object],
        agentRemove: [Function],
        drain: [Function: ondrain],
        error: [Function: socketErrorListener] },
     _maxListeners: 10,
     _writableState: 
      { highWaterMark: 16384,
        objectMode: false,
        needDrain: false,
        ending: false,
        ended: false,
        finished: false,
        decodeStrings: false,
        defaultEncoding: 'utf8',
        length: 0,
        writing: false,
        sync: false,
        bufferProcessing: false,
        onwrite: [Function],
        writecb: null,
        writelen: 0,
        buffer: [],
        errorEmitted: false },
     writable: true,
     allowHalfOpen: false,
     onend: [Function: socketOnEnd],
     destroyed: false,
     bytesRead: 1374,
     _bytesDispatched: 64,
     _pendingData: null,
     _pendingEncoding: '',
     parser: 
      { _headers: [],
        _url: '',
        onHeaders: [Function: parserOnHeaders],
        onHeadersComplete: [Function: parserOnHeadersComplete],
        onBody: [Function: parserOnBody],
        onMessageComplete: [Function: parserOnMessageComplete],
        socket: [Circular],
        incoming: [Circular],
        maxHeaderPairs: 2000,
        onIncoming: [Function: parserOnIncomingClient] },
     _httpMessage: 
      { domain: null,
        _events: {},
        _maxListeners: 10,
        output: [],
        outputEncodings: [],
        writable: true,
        _last: true,
        chunkedEncoding: false,
        shouldKeepAlive: true,
        useChunkedEncodingByDefault: false,
        sendDate: false,
        _headerSent: true,
        _header: 'GET / HTTP/1.1\r\nHost: www.google.com\r\nConnection: keep-alive\r\n\r\n',
        _hasBody: true,
        _trailer: '',
        finished: true,
        _hangupClose: false,
        socket: [Circular],
        connection: [Circular],
        agent: [Object],
        socketPath: undefined,
        method: 'GET',
        path: '/',
        _headers: [Object],
        _headerNames: [Object],
        parser: [Object],
        res: [Circular] },
     ondata: [Function: socketOnData] },
  _consuming: false,
  _dumped: false,
  httpVersionMajor: 1,
  httpVersionMinor: 1,
  upgrade: false,
  req: 
   { domain: null,
     _events: {},
     _maxListeners: 10,
     output: [],
     outputEncodings: [],
     writable: true,
     _last: true,
     chunkedEncoding: false,
     shouldKeepAlive: true,
     useChunkedEncodingByDefault: false,
     sendDate: false,
     _headerSent: true,
     _header: 'GET / HTTP/1.1\r\nHost: www.google.com\r\nConnection: keep-alive\r\n\r\n',
     _hasBody: true,
     _trailer: '',
     finished: true,
     _hangupClose: false,
     socket: 
      { _connecting: false,
        _handle: [Object],
        _readableState: [Object],
        readable: true,
        domain: null,
        _events: [Object],
        _maxListeners: 10,
        _writableState: [Object],
        writable: true,
        allowHalfOpen: false,
        onend: [Function: socketOnEnd],
        destroyed: false,
        bytesRead: 1374,
        _bytesDispatched: 64,
        _pendingData: null,
        _pendingEncoding: '',
        parser: [Object],
        _httpMessage: [Circular],
        ondata: [Function: socketOnData] },
     connection: 
      { _connecting: false,
        _handle: [Object],
        _readableState: [Object],
        readable: true,
        domain: null,
        _events: [Object],
        _maxListeners: 10,
        _writableState: [Object],
        writable: true,
        allowHalfOpen: false,
        onend: [Function: socketOnEnd],
        destroyed: false,
        bytesRead: 1374,
        _bytesDispatched: 64,
        _pendingData: null,
        _pendingEncoding: '',
        parser: [Object],
        _httpMessage: [Circular],
        ondata: [Function: socketOnData] },
     agent: 
      { domain: null,
        _events: [Object],
        _maxListeners: 10,
        options: {},
        requests: {},
        sockets: [Object],
        maxSockets: 5,
        createConnection: [Function] },
     socketPath: undefined,
     method: 'GET',
     path: '/',
     _headers: { host: 'www.google.com' },
     _headerNames: { host: 'Host' },
     parser: 
      { _headers: [],
        _url: '',
        onHeaders: [Function: parserOnHeaders],
        onHeadersComplete: [Function: parserOnHeadersComplete],
        onBody: [Function: parserOnBody],
        onMessageComplete: [Function: parserOnMessageComplete],
        socket: [Object],
        incoming: [Circular],
        maxHeaderPairs: 2000,
        onIncoming: [Function: parserOnIncomingClient] },
     res: [Circular] } }

2 个答案:

答案 0 :(得分:0)

http.get返回一个响应对象,通过错误事件捕获错误:

http.get("http://www.google.com/index.html", function(res) {
  console.log("Got response: " + res.statusCode);
}).on('error', function(e) {
  console.log("Got error: " + e.message);
});

Source

所以你的代码每次都会完美执行,除非你调用响应“错误”。

function(err, response)更改为:function(response)

另外,对于评论部分,

        res.pipe(concat(function (data) {
            //
        }));

        res.on("error", callback);

答案 1 :(得分:0)

http.get的回调只获得一个参数,它是响应:

http.get("http://www.google.com/index.html", function(res) {
  console.log("Got response: " + res.statusCode);
}).on('error', function(e) {
  console.log("Got error: " + e.message);
});

Doc