Calling function depending on updated fields - node.js

I want to call different functions depending on the updated model fields.
My code looks like:
update(req, res){
return LED
.findById(req.params.LEDId)
.then(LED => {
if (!LED) {
return res.status(400).send({
message: 'LED Not Found',
});
}
return LED
.update(req.body, {fields: Object.keys(req.body)})
.then(() => res.status(200).send(LED))
.catch((error) => res.status(400).send(error));
})
.catch((error) => res.status(400).send(error));
},
So my plan was to integrate some if-clauses to get the changed value and call some functions depending on the changes.
If-Clauses:
if(req.body.status || LED.status){
BLE.changeStatus(req.body.device_ID,req.body.status);
}else if(req.body.prog || LED.prog){
BLE.changeProg(req.body.device_ID,req.body.prog);
}else if(req.body.white || LED.white){
BLE.changeWhite(req.body.device_ID,req.body.white);
}else if(req.body.color || LED.color){
BLE.changeColor(req.body.device_ID,req.body.color);
}else if(req.body.brightness || LED.brightness){
BLE.changeBrightness(req.body.device_ID,req.body.brightness);
}
Where do I need to integrate these if-clauses that the functions can be called?
I've tried to integrate it in a .then() before I send the field updates to DB but I get the following error while trying to start the server:
SyntaxError: Unexpected token if
at createScript (vm.js:53:10)
at Object.runInThisContext (vm.js:95:10)
at Module._compile (module.js:543:28)
at Object.Module._extensions..js (module.js:580:10)
at Module.load (module.js:488:32)
at tryModuleLoad (module.js:447:12)
at Function.Module._load (module.js:439:3)
at Module.require (module.js:498:17)
at require (internal/module.js:20:19)
at Object.<anonymous> (/home/pi/projekt/server/controllers/index.js:1:75)
[nodemon] app crashed - waiting for file changes before starting...
EDIT
I'm a bit further now..
I've wrote the update function like:
update(req, res){
return LED
.findById(req.params.LEDId)
.then(LED => {
if (!LED) {
return res.status(404).send({
message: 'LED Not Found',
});
}
if(req.body.status){
changeStatus(req.params.LEDId,req.body.status);
console.log('STATUS CHANGED');
} if(req.body.prog){
changeProg(req.params.LEDId,req.body.prog);
console.log('PROG CHANGED');
} if(req.body.white){
changeWhite(req.params.LEDId,req.body.white);
console.log('WHITE CHANGED');
} if(req.body.color){
changeColor(req.params.LEDId,req.body.color);
console.log('COLOR CHANGED');
} if(req.body.brightness){
console.log('BEFORE BRIGHNTESS CHANGED')
changeBrightness(req.params.LEDId,req.body.brightness)
console.log('BRIGHNTESS CHANGED')
}
return LED
.update(req.body, {fields: Object.keys(req.body)})
.then(() => res.status(200).send(LED))
.catch((error) => res.status(400).send(error));
})
.catch((error) => res.status(400).send(error));
},
I've tested it and it jumps to the changeBrightness function. There I want to work with noble. Code looks like this:
changeBrightness(LEDId,updateBrightness){
console.log('BEGINN CHANGEBRIGHTNESS FUNCTION')
var uuid = "4711";
var brightness = updateBrightness;
console.log('BRIGHTNESS', brightness)
console.log('UUID', uuid)
console.log('AFTER CHANGEBRIGHTNESS VAR')
// Connect to client, find Service, find Characteristic and write status
noble.connect(uuid, function(error){
noble.discoverServices([lightningServiceUuid], function(error, service){
var tempLightningService = service[0];
writeFile("SUCCESS -- Discovered Service on UUID");
tempLightningService.discoverCharacteristics([brightnessCharacteristic], function(error, characteristics){
var tempBrightnessCharacteristic = characteristics[0];
writeFile("SUCCESS -- Discovered Characterisitc on UUID");
console.log('IN THE MIDDLE OF CHANGEBRIGHTNESS FUNCTION')
tempBrightnessCharacteristic.write(new Buffer(brightness), true, function(error){
writeFile("SUCCESS -- Wrote brightness characteristic");
});
});
});
});
//Disconnect from client
noble.disconnect(function(error){
writeFile("SUCCESS -- Disconnected from Client");
});
console.log('END CHANGEBRIGHTNESS FUNCTION')
}
I'm currently working with a fake uuid for testing purposes.. So my output looks like this when I start the server and execute a update request:
[nodemon] restarting due to changes...
[nodemon] starting `node ./bin/www`
Executing (default): SELECT "id", "device_id", "name", "group", "status", "device_type", "prog", "white", "color", "brightness", "createdAt", "updatedAt" FROM "LEDs" AS "LED" WHERE "LED"."id" = '1';
BEFORE BRIGHNTESS CHANGED
BEGINN CHANGEBRIGHTNESS FUNCTION
BRIGHTNESS 5
UUID 4711
AFTER CHANGEBRIGHTNESS VAR
PUT /api/led/1 400 357.728 ms - 2
Why does it stop before the noble function? What do I need to change?

Related

cant send a message to a specific channel

I have a simple dc bot, code goes like this. I tried to simplfy it to make it more readable
const client = new Discord.Client();
...
client.on('ready', () => {
client.channels.cache.get('315445287374028800').send("works here");
});
setInterval(( () =>{
try{
removeHTML(downloadHTML);
} catch(err){
console.log(err);
}
}),30000);
...
...
let removeHTML = function(callback){
client.channels.cache.get('315445287374028800').send("WORKS HERE");
readHTML();
...
}
let readHTML = function(){
console.log("dolar is read");
//client.channels.cache.get('315445287374028800').send("DOESNT WORK HERE");
fs.readFile(dir + '/index.html' , 'utf-8', function(err,html){
if(err)
console.log(err);
else{
//client.channels.cache.get('315445287374028800').send("DOESNT WORK HERE");
if(isPeak){
//client.channels.cache.get('315445287374028800').send("DOESNT WORK HERE");
}
}
});
}
seems like send function doesnt work in callback functions but how can i fix this?
Error type: same error for all ("DOESNT WORK HERE") lines :
TypeError: Cannot read property 'send' of undefined
at readHTML (C:\Users\user\Desktop\Discord Bot\index.js:142:18)
at Object.<anonymous> (C:\Users\user\Desktop\Discord Bot\index.js:182:1)
at Module._compile (internal/modules/cjs/loader.js:1015:30)
at Object.Module._extensions..js (internal/modules/cjs/loader.js:1035:10)
at Module.load (internal/modules/cjs/loader.js:879:32)
at Function.Module._load (internal/modules/cjs/loader.js:724:14)
at Function.executeUserEntryPoint [as runMain]
I have turned all functions to async-await instead and it worked

Running NodeJS App with Socket IO on Shared CPanel server Unexpected token

I created a very simple socket IO app which receives a message and posts it back in a socket group.
The app is running successfully on my Windows machine with Node.js v12.14.0. But I want to get rid of my port forwarding so asked my hoster if it was possible to run the Node.js app on Cpanel. They were not a fan, but opened it up.
I had to install the dependencies manually but finally got no more dependency error while starting the app, but ended up with the error below. After doing some google-ing it probably has to do with the Node.js version on the server which is v6.16.0 . The hoster says they can't get this updated as it comes with cpanel. Now I was hoping there is a way to get my app.js running on this version.
Error:
enter code here[username#server app]$ node /home/username/domains/website.nl/app/app.js
/home/username/domains/website.nl/app/node_modules/ws/lib/websocket.js:347
...options
^^^
SyntaxError: Unexpected token ...
at createScript (vm.js:56:10)
at Object.runInThisContext (vm.js:97:10)
at Module._compile (module.js:549:28)
at Object.Module._extensions..js (module.js:586:10)
at Module.load (module.js:494:32)
at tryModuleLoad (module.js:453:12)
at Function.Module._load (module.js:445:3)
at Module.require (module.js:504:17)
at require (internal/module.js:20:19)
at Object.<anonymous> (/home/username/domains/website.nl/app/node_modules/ws/index.js:3:19)
[username#server app]$ node -v
v6.16.0
The app:
var fs = require('fs');
var https = require('https');
var prvKey = fs.readFileSync('/home/username/ssl/keys/1.key').toString();
var prvCert = fs.readFileSync('/home/username/ssl/certs/1.crt').toString();
var server = https.createServer({key:prvKey,cert:prvCert});
var serverPort = 3000;
// var server = https.createServer();
var io = require('socket.io')(server);
server.listen(serverPort, function() {
console.log('server up and running at %s port', serverPort);
});
io.on("connection", function(socket) {
console.log("user connected: " + socket.id + " - " + socket.request.connection.remoteAddress);
var activequizid = null;
socket.on('jsondata', function(data){
if(data.join.join == "true"){
console.log(socket.id + " join group " + data.join.quizid)
socket.join(data.join.quizid)
}
})
socket.on('jsondataupdate', function(data){
console.log(data.update)
if(data.update.status){
socket.to(data.update.quizid).emit('update', data.update);
}
})
socket.on("disconnect", function(socketd) {
console.log(socketd)
console.log(this.id)
});
socket.on('connection', function () {
console.log('connection!')
})
socket.on('reconnecting', function () {
console.log('reconnecting!')
})
socket.on('reconnect', function () {
console.log('reconnect!')
})
socket.on('disconnect', function () {
console.log('disconnect!')
})
});
console.log("sever online")
websocket.js (partly function with error (look for "...options")) :
send(data, options, cb) {
if (this.readyState === WebSocket.CONNECTING) {
throw new Error('WebSocket is not open: readyState 0 (CONNECTING)');
}
if (typeof options === 'function') {
cb = options;
options = {};
}
if (typeof data === 'number') data = data.toString();
if (this.readyState !== WebSocket.OPEN) {
sendAfterClose(this, data, cb);
return;
}
const opts = {
binary: typeof data !== 'string',
mask: !this._isServer,
compress: true,
fin: true,
...options
};
if (!this._extensions[PerMessageDeflate.extensionName]) {
opts.compress = false;
}
this._sender.send(data || EMPTY_BUFFER, opts, cb);
}

Express : using await before bcrypt.compare gives error

I am trying to use bcrypt to compare user's password with stored password.
But Express is giving error is I use await before bcrypt.compare
Here is the code :
app.post ('/users/login', (req, res) => {
const user = users.find(user=> user.name === req.body.user)
if (user == null) {
return res.status(400).send('Can Not find user');
} else {
try{
if ( await bcrypt.compare(req.body.password, user.password)) {
res.send("Success");
} else {
res.send("Incorrect PAssword");
}
} catch {
return res.status(500).send('Some Error has occurred');
}
}
});
I am getting this error :
C:\Data\Ashish\projects\jwtAuthentication\app.js:32
if ( await bcrypt.compare(req.body.password, user.password)) {
^^^^^^
SyntaxError: Unexpected identifier
at Module._compile (internal/modules/cjs/loader.js:723:23)
at Object.Module._extensions..js (internal/modules/cjs/loader.js:789:10)
at Module.load (internal/modules/cjs/loader.js:653:32)
at tryModuleLoad (internal/modules/cjs/loader.js:593:12)
at Function.Module._load (internal/modules/cjs/loader.js:585:3)
at Function.Module.runMain (internal/modules/cjs/loader.js:831:12)
at startup (internal/bootstrap/node.js:283:19)
at bootstrapNodeJSCore (internal/bootstrap/node.js:622:3)
[nodemon] app crashed - waiting for file changes before starting...
Please help to find the mistake..
Regards,
Ashish
You forgot to add async to the callback function.
app.post ('/users/login', (req, res) => {
Should be:
app.post ('/users/login', async (req, res) => {
Await will work only with async functions.
It is different from the chrome console. In the console you can directly use await keyword, but in case of node.js, you need to specify async nature of the parent function in which you want to use await.
For further reference, you can refer to this link.

SyntaxError: Unexpected token function in async function?

Hi everyone I'm beginner in Nodejs and mongoose.I have tried to insert and retrieve the data in mongoose.I'm using async await function to execute one by one (sequence).can anyone help me? Thanks in advance....
i.e: I want to execute (Async await)concept (SEQUENCE STEP)
1.connect the db
2.create the user
3.find the user.
I'm getting the error :
async function calltaskone(){
^^^^^^^^
SyntaxError: Unexpected token function
at Object.exports.runInThisContext (vm.js:78:16)
at Module._compile (module.js:543:28)
at Object.Module._extensions..js (module.js:580:10)
at Module.load (module.js:488:32)
at tryModuleLoad (module.js:447:12)
at Function.Module._load (module.js:439:3)
at Module.runMain (module.js:605:10)
at run (bootstrap_node.js:420:7)
at startup (bootstrap_node.js:139:9)
at bootstrap_node.js:535:3
Code for your reference:
'use strict';
const mongoose=require('mongoose');
const calldbconnect=()=>{
return new Promise((resolve,reject)=>{
if(true){
mongoose.connect('mongodb://vdsd:vdwdwh12dw3,#ds11dwdw.mlab.com:1w5664/vorganisation',{useNewUrlParser:true},(err,db)=>{
if(err){
console.log(err);
reject('Db is not connected');
}
else{
resolve('Db is connected');
}
});
}
});
}
const schemadesign=new mongoose.Schema({
clientName:String,
clientId:Number,
clientAddress:String
});
const modeldata=mongoose.model('clientInfo',schemadesign);
const data=[{
clientName:'VIGNESH Mack',
clientId:4128,
clientAddress:'UK'
},{
clientName:'VIGNESH Tokyo',
clientId:4988,
clientAddress:'USA'
}];
function calldatasave(){
return new Promise((resolve,reject)=>{
modeldata.create(data,(err,a,b)=>{
if(err){
reject(`Error occured while data saved ${err}`);
}
else{
resolve('Data saved successfully');
}
});
});
}
const calldatafind=()=>{
return new Promise((resolve,reject)=>{
if(true){
console.log('try to find');
modeldata.find({'clientId':4988},(err,data)=>{
if(err){
reject(`Error occured while find data: ${err}`)
}
else{
console.log(data);
resolve('Data found');
}
});
}
});
}
async function calltaskone(){
const a=await calldbconnect();
console.log(a);
const b=await calldatasave();
console.log(b);
const c=await calldatafind();
console.log(c);
}
calltaskone();
I believe you're using a older version of Node. Async functions are not supported by Node versions older than version 7.6. You can check here.
If you want to use async/await then you need to transpile using Babel for your node version.
Edit:
As you said you are using v7.3, you can use (from v7.0 to v7.5) the --harmony flag to enable the experimental features. To know more about the flag, check this out: What does `node --harmony` do?

Node JS - SyntaxError: Unexpected token

I'm trying to figure out why I'm getting this unexpected token .
Object.entries(sockets).forEach(([key, cs])) => {
^
SyntaxError: Unexpected token .
at createScript (vm.js:80:10)
at Object.runInThisContext (vm.js:139:10)
at Module._compile (module.js:607:28)
at Object.Module._extensions..js (module.js:654:10)
at Module.load (module.js:556:32)
at tryModuleLoad (module.js:499:12)
at Function.Module._load (module.js:491:3)
at Function.Module.runMain (module.js:684:10)
at startup (bootstrap_node.js:187:16)
at bootstrap_node.js:608:3
Object.entries(sockets).forEach(([key, cs])) => {
process.stdout.write('\u001B[2J\u001B[0;0f'); //again clear node terminal
const server = require('net').createServer(); // here use the createServer method from net module
let counter = 0;
let sockets = {};
server.on('connection', socket => {
socket.id = counter++; //everytime a client connects assign an id, and add to the counter for next socket Id
//sockets[sockets.id] = socket;
console.log('Client is connected!');
socket.write('Hi, your name?\n');
socket.on('data', data => {
if(!socket[socket.id]) {
socket.name = data.toString().trim();
socket.write(`Welcome ... $[socket.name}!\n`);
sockets[socket.id] = socket;
return;
}
Object.entries(sockets).forEach(([key, cs])) => {
if (socket.id == key)
return;
cs.write(`${socket.name}: `);
// console.log('data is', data);
cs.write(data);
});
});
socket.on('end', () => {
delete sockets[socket.id];
console.log('Client is now disconnected');
});
});
This is a simple chat program written in node that allows multiple clients to connect and chat among each other.
You added an extra parenthesis in
Object.entries(sockets).forEach(([key, cs]) =>{}) this line.

Resources