Running NodeJS App with Socket IO on Shared CPanel server Unexpected token - node.js

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);
}

Related

Failed to connect with RabbitMQ server when sending large amount of messages

I am using Cloudamqp to connect with RabbitMq when I am trying to send 10 messages its publishing data successfully to the queue but when I am trying to send 2,000 messages its showing connection failed error shown below:
Error Error: connect ECONNREFUSED 15.206.75.114:5671
at TCPConnectWrap.afterConnect [as oncomplete] (node:net:1247:16) {
errno: -111,
code: 'ECONNREFUSED',
syscall: 'connect',
address: '15.206.75.114',
port: 5671
}
Error Error: Expected ConnectionOpenOk; got <ConnectionClose channel:0>
at /home/digvijay/test/test-lorien/node_modules/amqplib/lib/connection.js:167:14
at /home/digvijay/test/test-lorien/node_modules/amqplib/lib/connection.js:159:12
at TLSSocket.recv (/home/digvijay/test/test-
lorien/node_modules/amqplib/lib/connection.js:507:12)
I am reading the Excel file using XLSX library and sending those rows to the queue. Below is my code:
const express = require('express');
const XLSX = require("xlsx");
const amqp = require('amqplib/callback_api');
const app = express();
const port = process.env.PORT || 3300;
// Reading our test file
const file = XLSX.readFile('./limit9.xlsx')
app.get('/', (req, res) => {
const sheets = file.SheetNames;
for (let i = 0; i < sheets.length; i++) {
const temp = XLSX.utils.sheet_to_json(
file.Sheets[file.SheetNames[i]])
temp.forEach((res) => {
sendData(res); //Here sending data to the queue
});
}
});
function sendData(res) {
amqp.connect(`amqps://nuogafvveJoldl_RhEyfs7qJzX0BIRep6J8rFIN-0#puffin.rmq2.cloudamqp.com/xxxxxxx`, (err, connection) => {
if (err) {
console.log("Error",err);
}
else {
connection.createChannel((err, channel) => {
if (err) {
throw err;
}
else {
let queu = "review_data";
channel.assertQueue(queu, {
durable: false
});
var json = JSON.stringify(res);
channel.sendToQueue(queu, Buffer.from(json));
}
});
}
});
}
Why is it throwing connection error when I am sending large amount of messages but works fine for sending few messages?

How do I fix my Discord bot being offline?

I got recently interested in discord bots coding and I don't know what the problem is with this error, I tried different solutions I can find but all of them are not working and my bot is still offline on the server.
Error: Invalid transport, must be an object with a log method.
at new LegacyTransportStream (C:\Users\redacted\Desktop\NinyaBot\node_modules\winston-transport\legacy.js:18:11)
at DerivedLogger.add (C:\Users\redacted\Desktop\NinyaBot\node_modules\winston\lib\winston\logger.js:345:11)
at Object.winston.<computed> [as add] (C:\Users\redacted\Desktop\NinyaBot\node_modules\winston\lib\winston.js:110:68)
at Object.<anonymous> (C:\Users\redacted\Desktop\NinyaBot\bot.js:6:8)
at Module._compile (internal/modules/cjs/loader.js:1133:30)
at Object.Module._extensions..js (internal/modules/cjs/loader.js:1153:10)
at Module.load (internal/modules/cjs/loader.js:977:32)
at Function.Module._load (internal/modules/cjs/loader.js:877:14)
at Function.executeUserEntryPoint [as runMain] (internal/modules/run_main.js:74:12)
at internal/main/run_main_module.js:18:47
this is the code i used that i found online.
var Discord = require('discord.io');
var logger = require('winston');
var auth = require('./auth.json');
// Configure logger settings
logger.remove(logger.transports.Console);
logger.add(logger.transports.Console, {
colorize: true
});
logger.level = 'debug';
// Initialize Discord Bot
var bot = new Discord.Client({
token: auth.token,
autorun: true
});
bot.on('ready', function (evt) {
logger.info('Connected');
logger.info('Logged in as: ');
logger.info(bot.username + ' - (' + bot.id + ')');
});
bot.on('message', function (user, userID, channelID, message, evt) {
// Our bot needs to know if it will execute a command
// It will listen for messages that will start with `!`
if (message.substring(0, 1) == '!') {
var args = message.substring(1).split(' ');
var cmd = args[0];
args = args.splice(1);
switch(cmd) {
// !ping
case 'ping':
bot.sendMessage({
to: channelID,
message: 'Pong!'
});
break;
// Just add any case commands if you want to..
}
}
});
The error showed in console is about line 6, however maybe is not what makes the
bot appears offline.
logger.add(logger.transports.Console, {
colorize: true
});
And should be fixed with something like
logger.add(new logger.transports.Console({
format: winston.format.combine(
winston.format.colorize(),
winston.format.simple()
)
}));
Watch to new word. Now transports require a new object to work and for colorize you can set it combining the formats.
Here you can find more info about it https://www.npmjs.com/package/winston#common-transport-options
I recommend using discord.js https://discordjs.guide/creating-your-bot/#creating-the-bot-file
Use this code and it work just fine:
const Discord = require('discord.js');
const client = new Discord.Client();
client.once('ready', () => {
console.log('Ready!');
});
client.login('your-token-goes-here');

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.

Calling function depending on updated fields

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?

async await with nodejs 7

I've installed nodejs 7.3.0 and I have this code:
let getContent = function (url) {
// return new pending promise
return new Promise((resolve, reject) => {
// select http or https module, depending on reqested url
const lib = url.startsWith('https') ? require('https') : require('http');
const request = lib.get(url, (response) => {
// handle http errors
if (response.statusCode < 200 || response.statusCode > 299) {
reject(new Error('Failed to load page, status code: ' + response.statusCode));
}
// temporary data holder
const body = [];
// on every content chunk, push it to the data array
response.on('data', (chunk) => body.push(chunk));
// we are done, resolve promise with those joined chunks
response.on('end', () => resolve(body.join('')));
});
// handle connection errors of the request
request.on('error', (err) => reject(err))
})
};
let get = async function (url) {
var content = await getContent(url);
return content;
}
var html = get('https://developer.mozilla.org/it/');
In debug I receive this:
let get = async function (url) {
^^^^^^^^
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)
Node 7.3.0 does not support async/await without a feature flag. Spawning node like this should do the trick:
node --harmony-async-await app.js
EDIT
Node now officially supports async/await by default in version 7.6.0, which comes from updating V8, Chromium’s JavaScript engine, to version 5.5.

Resources