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.
Related
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
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);
}
I am trying to make a discord bot for my server and everytime I try to start the bot it gives me the same error every time.
I haven't tried anything else because a google search does not find the error.
I was following a YouTube video that was made in 2017.
const Discord = require("discord.js");
const client = new Discord.Client();
const config = require("./config.json");
var prefix = config.prefix;
//Startup
client.login(config.token);
client.on("ready", () => {
console.log(`Online ${new Date()}`);
client.user.setGame("Online");
});
client.on("message", async message => {
//Ingore bots
if(message.author.bot) return;
//Prefix in command
if(message.content.indexOf(config.prefix) !==0) return;
const args = message.content.slice(config.prefix.legth).trim().split(/
+/g);
const command = args.shift().toLowerCase();
if (command === "ping") {
message.reply("Pong!");
}
});
I expected the bot to start fully but gave me the following error
"internal/modules/cjs/loader.js:800
throw err;
^
SyntaxError: C:\Users\adoss\Desktop\DiscordBot\config.json: Unexpected
string in JSON at position 37
at JSON.parse (<anonymous>)
at Object.Module._extensions..json
(internal/modules/cjs/loader.js:797:27)
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 Module.require (internal/modules/cjs/loader.js:692:17)
at require (internal/modules/cjs/helpers.js:25:18)
at Object.<anonymous> (C:\Users\adoss\Desktop\DiscordBot\bot.js:3:16)
at Module._compile (internal/modules/cjs/loader.js:778:30)
at Object.Module._extensions..js (internal/modules/cjs/loader.js:789:10)"
const Discord = require('discord.js');
const bot = new Discord.Client();
let cofig = require('./botconfig.json');
let token = config.token;
let prefix = config.prefix;
bot.on('ready', () => {
console.log(`Запустился бот ${bot.user.username}`);
});
bot.on('message', msg => {
if (msg.content === 'ping') {
msg.reply('Pong!');
}
});
bot.login(token);`
My bot is supposed to answer by Pong! when I type the ping in a channel. It's a simple ping test to check if the bot is alive and behave correctly. However I have an error when I try to make it work.
Error:
SyntaxError: C:\Users\mrakp\OneDrive\Рабочийстол\mamapapads\botconfig.json: Unexpected end of JSON input
at JSON.parse (<anonymous>)
at Object.Module._extensions..json (internal/modules/cjs/loader.js:801:27)
at Module.load (internal/modules/cjs/loader.js:643:32)
at Function.Module._load (internal/modules/cjs/loader.js:556:12)
at Module.require (internal/modules/cjs/loader.js:683:19)
at require (internal/modules/cjs/helpers.js:16:16)
at Object.<anonymous> (C:\Users\mrakp\OneDrive\Рабочий стол\mamapapads\bot.js:3:13)
at Module._compile (internal/modules/cjs/loader.js:776:30)
at Object.Module._extensions..js (internal/modules/cjs/loader.js:787:10)
at Module.load (internal/modules/cjs/loader.js:643:32)
Well first off, you can't do
const cofig = require("./botconfig.json")
Then not use the declaration in order to get the token.
In your case, bot.login(token) would actually be bot.login(cofig.token)
But you can also do
const { token } = require("./botconfig.json")
//Rest of code
bot.login(token)
Which would get the token directly, instead of having to use a declaration in order to reference it.
fallowing code returns list of models
var models = app.models();
models.forEach(function(Model) {
console.log(Model.modelName);
});
User
AccessToken
ACL
RoleMapping
Role
Registration
Assets
when I using fallowing code to use Registration or Asstes:
D:\apps\newapps\testapp\node_modules\loopback\lib\application.js:129
assert(Model.prototype instanceof Model.registry.getModel('Model'),
^
TypeError: Cannot read property 'prototype' of undefined
at Function.app.model (D:\apps\newapps\testapp\node_modules\loopback\lib\application.js:129:17)
at Object.<anonymous> (D:\apps\newapps\testapp\server\server.js:38:5)
at Module._compile (module.js:573:30)
at Object.Module._extensions..js (module.js:584:10)
at Module.load (module.js:507:32)
at tryModuleLoad (module.js:470:12)
at Function.Module._load (module.js:462:3)
at Function.Module.runMain (module.js:609:10)
at startup (bootstrap_node.js:158:16)
at bootstrap_node.js:598:3
I am not expert of loopback but try this code:
var Registration = app.models.Registration;
console.log(Registration);
app.model(Registration);
User is the model name.
var user = app.models.User;
resetPassword is function name of the user model, which
take two parameter new_pwd and token,
user.resetPassword({
new_pwd: new_password,
token
}, (err, data) => {
if (err || !data.status) {
return err || data;
} else {
return data;
}
});