Rendering variable to ejs template? - node.js

My ejs side (webpage) is updating the wrong variables every time I refresh the page,but each variable has a different name. I cannot figure out what is wrong.
My index.js is receiving messages from an esp8266 using MQTT, and then I render that to the ejs.
index.js
var topicTemp = "FromESPtoWeb/temp";
var topicMessagemoisture = "FromESPtoWeb/moisture";
var content = { doorMsg: "Door Closed" ,
windowMsg: "Window Closed",
tempMsg : "",
moistureMsg : "" ,
motionMsg: "Motion" };
client.on('connect', function () {
//Subscribe to topic "FromESPtoWeb/temp"
client.subscribe(topicTemp, function (err) {
if (err) {
alert("something went wrong on subscribe to message");
}
client.on('message', function (topicTemp, temp) {
console.log(temp.toString());
content.tempMsg = temp.toString();
});
})
//Subscribe to topic "FromESPtoWeb/moisture"
client.subscribe(topicMessagemoisture, function (err) {
if (err) {
alert("something went wrong on subscribe to message");
}
client.on('message', function (topicMoisture, moisture) {
console.log("new message on " + topicMoisture + " - " +
moisture.toString());
content.moistureMsg = moisture.toString();
});
})
})
/* GET home page. */
router.get('/', function(req, res) {
res.render('index', { content : content } );
});
index.ejs
<h4> <%= content.moistureMsg %> </h4>
<h4> <%= content.motionMsg %> </h4>
<h4> <%= content.windowMsg %> </h4>
<h4> <%= content.doorMsg %> </h4>
content.moistureMsg sometimes showing what is suppose to be to content.windowMsg , or content.doorMsg is showing the value that is suppose to be to content.motionMsg. A complete mess...

Use the request object!.
router.get('/', function(req, res) {
res.render('index', { content : req.content } );
});

My understanding was very wrong about client.on and subscribe. I rebuilt the whole code, and now it is working.
var topicTemp = "FromESPtoWeb/temp";
var topicDoor = "FromESPtoWeb/door";
var topicWindow = "FromESPtoWeb/window";
var topicMoisture = "FromESPtoWeb/moisture";
var topicMotion = "FromESPtoWeb/motion";
var content = { doorMsg: "Door Closed" , windowMsg: "Window Closed", tempMsg:"", moistureMsg:"", motionMsg: ""};
client.on('connect', function () {
client.on('message', function (topic, message) {
if(topic === topicTemp) {
temp(message);
}
if(topic === topicDoor) {
door(message);
}
if(topic === topicWindow) {
window(message);
}
if(topic === topicMoisture) {
moisture(message);
}
if(topic === topicMotion) {
motion(message);
}
});
client.subscribe(topicTemp, function (err) {
if (err) {
alert("something went wrong on subscribe to message");
}
});
client.subscribe(topicDoor, function (err) {
if (err) {
alert("something went wrong on subscribe to message");
}
});
client.subscribe(topicWindow, function (err) {
if (err) {
alert("something went wrong on subscribe to message");
}
});
client.subscribe(topicMoisture, function (err) {
if (err) {
alert("something went wrong on subscribe to message");
}
});
client.subscribe(topicMotion, function (err) {
if (err) {
alert("something went wrong on subscribe to message");
}
});
});
var temp = (message) => {
console.log(message.toString());
content.tempMsg = message.toString();
}
var door = (message) => {
if (message == "Door Open") {
console.log("Door open");
content.doorMsg = message;
}else if (message == "Door Closed") {
console.log("Door closed");
content.doorMsg = message;
}
}
var window = (message) => {
if (message == "Window Open") {
console.log("window open");
content.windowMsg = message;
}else if (message == "Window Closed") {
console.log("window closed");
content.windowMsg = message;
}
}
var moisture = (message) => {
console.log(message.toString());
content.moistureMsg = message.toString();
}
var motion = (message) => {
console.log(message.toString());
content.motionMsg = message.toString();
}
/* GET home page. */
router.get('/', function(req, res) {
res.render('index', { content : content } );
});

Related

Dequeue request in Azure Service Bus when queue length < 10 frequently returns null

I have been experimenting with Azure Service Bus queues in NodeJS. I have built the sender.js and listener.js based on their code sample in the documentation. Building a queue works fine. Dequeuing and deleting messages from the queue works fine until message length reaches 10. At this point, dequeue requests return null messages around 4 out of 5 times. If I keep looping the dequeue requests, eventually, it will dequeue and delete those last 10 messages. But, this seems highly inefficient. Has anyone else experience this problem?
listener.js
var azure = require('azure');
var async = require("async");
var connectionString = process.env.CONNECTION_STRING || "Endpoint=sb://endpoint"; // dev
console.log(process.env.CONNECTION_STRING);
var serviceBusService = azure.createServiceBusService(connectionString);
// var serviceBusService = azure.createServiceBusService();
exports.createQueue = function (req,res) {
var body = req.body;
serviceBusService.createQueueIfNotExists(body.queueName, function(error){
console.log(error);
if(!error){
// Queue exists
return res.send(200);
} else {
return res.send(500, error);
}
});
};
exports.sendMessageToQueue = function (req, res) {
var body = req.body;
var message = {
body: 'Test message',
customProperties: {
testproperty: 'TestValue'
}};
serviceBusService.sendQueueMessage(body.queueName, message, function(error){
if(!error){
// message sent
return res.send(200);
} else {
return res.send(500, error);
}
});
}
exports.receiveMessageFromQueue = function (req, res) {
var body = req.body;
serviceBusService.receiveQueueMessage(body.queueName, function(error, receivedMessage){
if(!error){
console.log(receivedMessage);
// Message received and deleted
return res.send(200,receivedMessage);
} else {
return res.send(500, error);
}
});
}
function _receiveMessageFromQueue(queueName,delayTimeIfQueueIsEmpty,callback) {
serviceBusService.receiveQueueMessage(queueName, function(error, receivedMessage){
console.log(error, receivedMessage);
// console.log(error);
if (error == 'No messages to receive') {
// call the rest of the code and have it execute after 30 seconds
setTimeout(function() {
callback(receivedMessage);
}, delayTimeIfQueueIsEmpty);
} else {
// callback immediately
callback(receivedMessage);
}
});
}
function _sendQueueMessage(queueName,message,callback) {
serviceBusService.sendQueueMessage(queueName, message, function(error){
console.log(error);
callback();
});
}
function listenMessageQueue(concurrency,delayTimeIfQueueIsEmpty,queueName) {
var taskHandler = function(task, done) {
_receiveMessageFromQueue(task.queueName, delayTimeIfQueueIsEmpty, function(message) {
if (message) {
console.log('hello ' + message.body);
}
myQueue.push({ id: task.id + 1, queueName: queueName, url: "http://localhost/get-person/" + task.id + 1});
done();
});
};
var queueSize = concurrency;
var myQueue = async.queue(taskHandler, queueSize);
myQueue.drain = function() {
console.log("All the work has been done.");
}
for(var i = 0; i < concurrency; i++) {
myQueue.push({ id: i, queueName: queueName, url: "http://localhost/get-person/"+i });
}
}
delayTimeIfQueueIsEmpty = 30000; // 30s
concurrency = 2;
queueName = "jobs";
// listen and dequeue message from azure message bus
listenMessageQueue(concurrency,delayTimeIfQueueIsEmpty,queueName);
sender.js
var azure = require('azure');
var async = require("async");
var connectionString = process.env.CONNECTION_STRING || "Endpoint=sb://endpoint";
console.log(process.env.CONNECTION_STRING);
var serviceBusService = azure.createServiceBusService(connectionString);
exports.createQueue = function (req,res) {
var body = req.body;
serviceBusService.createQueueIfNotExists(body.queueName, function(error){
console.log(error);
if(!error){
// Queue exists
return res.send(200);
} else {
return res.send(500, error);
}
});
};
exports.sendMessageToQueue = function (req, res) {
var body = req.body;
var message = {
body: 'Test message',
customProperties: {
testproperty: 'TestValue'
}};
serviceBusService.sendQueueMessage(body.queueName, message, function(error){
if(!error){
// message sent
return res.send(200);
} else {
return res.send(500, error);
}
});
}
exports.receiveMessageFromQueue = function (req, res) {
var body = req.body;
serviceBusService.receiveQueueMessage(body.queueName, function(error, receivedMessage){
if(!error){
console.log(receivedMessage);
// Message received and deleted
return res.send(200,receivedMessage);
} else {
return res.send(500, error);
}
});
}
function _receiveMessageFromQueue(queueName,delayTimeIfQueueIsEmpty,callback) {
serviceBusService.receiveQueueMessage(queueName, function(error, receivedMessage){
console.log(error, receivedMessage);
// console.log(error);
if (error == 'No messages to receive') {
// call the rest of the code and have it execute after 30 seconds
setTimeout(function() {
callback(receivedMessage);
}, delayTimeIfQueueIsEmpty);
} else {
// callback immediately
callback(receivedMessage);
}
});
}
function _sendQueueMessage(queueName,message,callback) {
serviceBusService.sendQueueMessage(queueName, message, function(error){
console.log(error);
callback();
});
}
function listenMessageQueue(concurrency,delayTimeIfQueueIsEmpty,queueName) {
var taskHandler = function(task, done) {
_receiveMessageFromQueue(task.queueName, delayTimeIfQueueIsEmpty, function(message) {
if (message) {
console.log('hello ' + message.body);
}
myQueue.push({ id: task.id + 1, queueName: queueName, url: "http://localhost/get-person/" + task.id + 1});
done();
});
};
var queueSize = concurrency;
var myQueue = async.queue(taskHandler, queueSize);
myQueue.drain = function() {
console.log("All the work has been done.");
}
for(var i = 0; i < concurrency; i++) {
myQueue.push({ id: i, queueName: queueName, url: "http://localhost/get-person/"+i });
}
}
function pushMessageQueue(concurrency,queueName) {
var taskHandler = function(task, done) {
var message = {
body: String(task.id),
customProperties: {
url: task.url
}};
_sendQueueMessage(task.queueName, message, function() {
console.log('hello ' + task.id);
myQueue.push({ id: task.id + 1, queueName: queueName, url: "http://localhost/get-person/" + task.id + 1});
done();
});
};
var queueSize = concurrency;
var myQueue = async.queue(taskHandler, queueSize);
myQueue.drain = function() {
console.log("All the work has been done.");
}
for(var i = 0; i < concurrency; i++) {
myQueue.push({ id: i, queueName: queueName, url: "http://localhost/get-person/"+i });
}
}
concurrency = 2;
queueName = "jobs";
pushMessageQueue(concurrency,queueName); // push message to queue for testing: 100 messages per call
finally was able to get through to Azure support and found the answer. ServiceBus by default enables partitioning. When making http requests (the NodeJS SDK for Azure ServiceBus makes http REST calls), when message count is low can result in a partitions with different sets of messages, as they have not had a chance to sync. This is resolved by creating a new Queue that disables partitioning or by increasing the keep alive or by using the DotNet SDK which allows https requests to be made.

Async await issue in nodejs

I am trying to send messages to mobile numbers using message bird API, i have completed the coding part but its not sending the messages, even i can see i have sent messages and being delivered in my message bird profile. I came to know that this issue can be due to not using async and await. Here is my code,
api.get('/sendmessage', function (req, res) {
var id = req.headers.authorization;
if (req.session.id) {
var userid = req.session.user[0].id;
var username = userInfo.find({ id: userid }, function (err, user) {
if (err) { res.send("New Error: " + err); }
else {
if (!_.isEmpty(user)) {
var contact = user[0].contact;
var messagebird = require('messagebird')('ACCESS_KEY_API'); // Api for testing
var params = {
'originator': 'MessageBird',
'recipients': [
contact
],
'body': 'Hello, world!'
};
messagebird.messages.create(params, function (err, response) {
if (err) {
return console.log("Error sent to Console: " + err);
}
else {
console.log(response);
return res.send(response);
}
});
}
else {
res.send("No Results");
}
}
});
}
});

nodejs callback Error: Can't set headers after they are sent

i'm new!
I can't cope with the problem!
Did I try adding 'return' or not?
thx!
'GET /edit': async (ctx, next) => {
cache.get('user', function (err, result) {
if (err) {
console.log(err);
return;
}
var user = JSON.parse(result);
if (user == null) {
ctx.render('login.html', {
title: '登录'
});
} else {
ctx.render('edit.html');
}
})
// ctx.redirect('/login');
}

node.js synchronous function call for authentication

i am completely newbie in node.js, and trying learn how it actually works. I know that by default all node.js function calls are asynchronous. Now i need LDAP authentication in my application where i need wait for the server response to check whether the user credentials are right or wrong.The ldap part is working fine but i am not sure on how to return data from a function call in synchronous way. below is the part of my code.
router.js
var express = require('express');
var router = express.Router();
var tools = require('./authenticateUser');
router.post('/authenticateUser', function(req, res) {
// In the below line i am calling the method which
// should return the userDN (a string)
tools.searchUser(req.body.user, req.body.passwd);
res.render('home.jade');
});
authenticateUser.js
module.exports = {
searchUser : function (username, password) {
adminDN = *************;
adminPassword = '*********';
baseDN = '***';
var ldap = require('ldapjs');
process.env.NODE_TLS_REJECT_UNAUTHORIZED = "0";
var adminClient = ldap.createClient({
url: '*******'
});
var opts = {
filter: '(&(objectClass=userProxyFull)(sAMAccountName=' + username + '))',
scope: 'sub',
attribute: ['sAMAccountName']
};
console.log('--- going to try to connect user ---');
try {
adminClient.bind(adminDN, adminPassword, function (error) {
if (error) {
console.log(error.message);
adminClient.unbind(function (error) {
if (error) {
console.log(error.message);
} else {
console.log('adminClient disconnected');
}
});
} else {
// Searching Client ID in LDS
adminClient.search(baseDN, opts, function (error, search) {
console.log('Searching.....' + userDN);
search.on('searchEntry', function (entry) {
if (entry.object) {
// Here i need to return the object back
//to the router.js from where i call in a synchronous way
adminClient.unbind(function (error) {
if (error) {
console.log(error.message);
}
});
}
});
search.on('error', function (error) {
console.error('error: ' + error.message);
});
});
}
});
} catch (error) {
console.log(error);
adminClient.unbind(function (error) {
if (error) {
console.log(error.message);
} else {
console.log('client disconnected');
}
});
} finally {
adminClient.unbind(function (error) {
if (error) {
console.log(error.message);
} else {
console.log('client disconnected');
}
});
}
},
};
You have to pass res.render('home.jade') as a function(the callback) to your searchUser function.
It should look like
tools.searchUser(req.body.user,
req.body.password,
res}
)
searchUser function
searchUser : function (username, password,res) {
...
finally(){
res.render('home.jade');
}
}

How to pass changes from middleware to socket.io?

I am using node.js with socket.io to push real time notifications to users. However, currently I am just sending back a query result done in my socket.io code and sending it back to the client but I need to let socket know about the changes that occur and to either update with the changes or re-query the db to check for the new number and send that to the client.
For example if a user gets a friend request then the notification count will change and I want socket.io to push the new notification count number to the user.
here is my socket.io code in my app.js file:
io.on('connection', function(socket) {
var sessionID = socket.handshake.sessionID,
session = new connect.middleware.session.Session({ sessionStore: sessionStore }, socket.handshake.session)
console.log('socket: new ' + sessionID)
socket.broadcast.emit('arpNewConn', session.passport.user)
var intervalID = setInterval(function() {
socket.handshake.session.reload(function() {
socket.handshake.session.touch().save()
})
socket.emit('pulse', { heartbeat: new Date().toString(), timestamp: new Date().getTime() })
}, 300 * 1000)
socket.on('disconnect', function() {
console.log('socket: dump ' + sessionID)
socket.broadcast.emit('arpLostConn', session.passport.user)
clearInterval(intervalID)
})
socket.emit('entrance', {message: 'Message works'});
dbnotif.findOne(userID, function (err, user) {
if(err) throw err;
notify = user.notifications;
socket.emit('notify', {notific: notify});
});
});
Here is the client side:
div#CheckSocket
script(src='http://localhost:3000/socket.io/socket.io.js')
script.
$(document).ready(function () {
console.log('socket');
var socket = io.connect('http://localhost:3000/');
console.log('entered1');
socket.on('entrance', function (data) {
console.log('entered');
console.log(data.message);
});
socket.on('notify', function (data) {
console.log('noting');
console.log(data.notific);
if(data.notific !== 0)
$('.notifications').html(data.notific);
});
socket.on('reconnecting', function(data) {
setStatus('reconnecting');
console.log('entered2');
});
function setStatus(msg) {
console.log('connection status: ' + msg);
console.log('entered5');
}
});
Here is the example of adding a friend in the route file:
exports.addContactPost = function(req, res, err) {
async.waterfall([
function(callback) {
var success;
var newFriend = new Friend ({
userId: req.signedCookies.userid,
friend_id: mongoose.Types.ObjectId(req.body.otherUser),
friend_status: 1
});
newFriend.save(function(err){
if(err) {
console.log(err);
} else {
console.log("saved it");
success = true;
}
});
callback(null, success)
},
function(success, callback) {
//if(success === true) {
var success2;
var newFriend2 = new Friend ({
userId: mongoose.Types.ObjectId(req.body.otherUser),
friend_id: req.signedCookies.userid,
friend_status: 2
});
newFriend2.save(function(err){
if(err) {
res.send("request not received");
} else {
success2 = true;
}
});
callback(null, success2);
//} else {
// res.send("error with request sent");
//}
},
function(success2, callback) {
console.log('callback3');
//if(success2 === true) {
var success3;
Notification.findOneAndUpdate({userId: mongoose.Types.ObjectId(req.body.otherUser)}, {
$inc: {notifications: 1}
}, function(err, notify) {
if(err) {
res.send(err);
} else {
console.log(notify);
if(notify.added_notifications === true) {
// enable mail and include general u have got a new request... do not include name because not storing it
}
}
success3 = true;
callback(null, success3);
}],
function(err, results) {
res.json({response: true});
console.log("Add successful");
});
};
Notes: dbnotif is a model being called by mongoose,
userID is a global variable available to the file
I helped him solve this question offline, but we ended up using an EventEmitter as a proxy.
// main.js
var EventEmitter = require('events').EventEmitter;
var emitter = new EventEmitter();
Then add it to each request as middleware:
// elsewhere in main.js
app.use(function(req, res, next) {
req.emitter = emitter;
next();
});
Then in external routes file:
// routes.js
exports.addContactPost = function(req, res, err) {
req.emitter.emit( 'some-key', whatever, data, you, want );
};

Resources