mahdi pishguy mahdi pishguy - 1 year ago 95
Node.js Question

Nodejs send to specific user get Cannot read property 'emit' of undefined error

i want to send message to specific user which connected and logging into server by this sample code, but i get this error:

Cannot read property 'emit' of undefined

this below code is my sample to test:

var socket = require(''),
express = require('express'),
app = express(),
server = require('http').createServer(app),
io = socket.listen(server),
port = process.env.PORT || 3000,
redis = require("redis"),
redisClient = redis.createClient();

var io_redis = require('');

io.adapter(io_redis({host: 'localhost', port: 6379}));

io.sockets.on('connection', function (socket) {

socket.on('login', function (data) {
login(data.username, data.password, function (success, value) {
if (success) {
socket.emit('login', {result: true, id: value});
} else {
socket.emit('login', {result: false});

socket.on('message', function (username) {
redisClient.get(username, function (err, socketId) {
io.sockets.connected[socketId].emit('message', 'Hey !!');

why i get this error: i search and read many pages of this solution but as far as i know my code seemd correct, but i don't know whats problem.

error is for this line of code:

io.sockets.connected[socketId].emit('message', 'Hey !!');

Answer Source
  1. not sure why you didn't provide the line number that failed. you have multiple emits.
  2. who says the socket is there when redis get finishes? you must check if exists.

//when you do set, wait for set to finish before doing emit('login') //also fixed you set, instead of array, to put key and value redisClient.set(data.username,, function (err, done) { if (err) { //now what? } else { socket.emit('login', {result: true, id: value}); } });

//when you do the get, check exists redisClient.get(username, function (err, socketId) { if (io.sockets.connected[socketId]) { io.sockets.connected[socketId].emit('message', 'Hey !!'); } });

  1. you have

    var socket = require(''),

and function (socket) {

so you defined socket twice. thats not great.