Callback function in node.js. TypeError: Cannot call method 'emit' of undefined


I’m still trying to get the hang of callbacks. Can someone explain why I cannot update my webpage using the callback from setInterval?

When I run the code, I get the error

/home/pi/Programming/RC Car/server_serialport.js:32
      socket.emit('leftPingStatus', {status: _leftPing});
TypeError: Cannot call method 'emit' of undefined
    at null.<anonymous> (/home/pi/Programming/RC Car/server_serialport.js:32:14)
    at wrapper [as _onTimeout] (timers.js:252:14)

My code:

var express = require('express');
var app = express()
    ,server = require('http').createServer(app)
    ,io = require('').listen(server)
    ,wire = require('i2c')
    ,sys = require('sys')
    ,exec = require('child_process').exec;

//Web page status
var _connected = false;
var _leftPing = 0;
var _rightPing = 0;

server.listen(9081, 'raspberrycar.local');
app.use(express.static(__dirname + '/public'));

io.sockets.on('connection', function (socket){
    _connected = true; //Connected
    socket.emit('serverStatus', {   status: 'Server Connected' }); //Client connected
    socket.emit('arduinoStatus', {   status: 'Arduino Connected' }); //Arduino connected
    socket.on('key', KeyReceived);  //Key received from client
    setInterval(transferData, 50); //Transfer data to/from arduino

    setInterval(function (socket){
        socket.emit('leftPingStatus', {status: _leftPing});
        socket.emit('rightPingStatus', {status: _rightPing});
    , 50) //Transfer data to/from webpage

io.sockets.on('disconnect', function (socket){
    _connected = false; //Connected

I would rather define my function separately, call it from setInterval and then pass the socket to the function. Is this possible?

Problem courtesy of: Joseph Roberts


You’re taking socket as an argument, but setInterval doesn’t pass arguments to its callback*. Just take advantage of the socket in the containing scope:

setInterval(function() { // Remove socket
    socket.emit('leftPingStatus', {status: _leftPing});
    socket.emit('rightPingStatus', {status: _rightPing});
, 50);

You can’t really define that function elsewhere, per se; you would need a function to return this function or a function that accepts socket, e.g.

setInterval(function() {
, 50);
Solution courtesy of: Ryan


There is currently no discussion for this recipe.

This recipe can be found in it's original form on Stack Over Flow.