简体   繁体   中英

http.ClientRequest socket doesn't emit a data event

I would like to get TTFB with http module. The only way (IMO) to do it, is to add listener to a socket data event. But it doesn't seem to work.

Here is a code example.

var http = require('http');

var request = http.request('http://nodejs.org/');
request.end();

request.on('socket', function(socket) {
    socket.once('data', function TTFB() {
        console.log('Never happen');
    });
});

request.on('response', function(response) {
    console.log('status code', response.statusCode);
    response.on('data', function noop(){});

    response.on('end', function() {
        console.log('Bytes read', request.socket.bytesRead);
    });
});

Socket doesn't have a data event. Try listening on connect.

request.on('socket', function(socket) {
    socket.once('connect', function TTFB() {
        //Socket has been assigned to a request.
    });
});

You can see the events that socket emits by inspecting the socket object.

_events: {
    end: {
        [Function: g] listener: [Function: onend]
    },
    finish: [Function: onSocketFinish],
    _socketEnd: [Function: onSocketEnd],
    free: [Function],
    close: [
        [Function],
        [Function: socketCloseListener]
    ],
    agentRemove: [Function],
    drain: [Function: ondrain],
    error: [Function: socketErrorListener],
    connect: {
        [Function: g] listener: [Function]
    }
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM