Tuesday, 15 May 2018

io.emit vs socket.emit vs socket.broadcast.emit

Send message to one client, like New user come, we show him "welcome message" 
socket.emit('message', "Welcome user to our Chat Group");

Sending to all clients except sender 
socket.broadcast.emit('message', "New user i.e joy joined our chat group."); 

Sending to all clients in 'game' room(channel) except sender
socket.broadcast.to('game').emit('message', 'sending to all clients in 'game' room(channel) except sender'); 

Sending to sender client, only if they are in 'game' room(channel)
socket.to('game').emit('message', 'sending to sender client, only if they are in game room'); 

Sending to individual socketid
socket.broadcast.to(socketid).emit('message', 'sending to individual socketid'); 

Sending to all clients, include sender
io.emit('message', "sending to all clients, include sender"); 

Sending to all clients in 'game' room(channel), include sender
io.in('game').emit('message', 'sending to all clients in game room'); 

sending to all clients in namespace 'myNamespace', include sender
io.of('myNamespace').emit('message', 'sending to all clients in namespace myNamespace');

for emiting to specific clients
io.sockets.socket('for emiting to specific clients'); 

send to all connected clients 
io.sockets.emit('send to all connected clients');

Monday, 14 May 2018

Nodejs Interview Questions and Answer 2 year Experience

Question: How to encrypt a value with SECRET KEY?
const {SHA256} = require("crypto-js");
var SECRET_KEY='secretkey';

var message='I am good.';
var hash=SHA256(message+SECRET_KEY).toString();
console.log(`Message: ${message}`);
console.log(`Hash: ${hash}`);

You need to install the crypto-js module.

Question: How to encrypt and decrypt the String?
const jwt = require('jsonwebtoken');
var SECRET_KEY='secretkey';

var data = {
  id: 10

var token = jwt.sign(data, SECRET_KEY);
console.log(token);//Give you long string 

var decoded = jwt.verify(token, SECRET_KEY);
console.log('decoded', decoded);