socket.io.users error from example - node.js

So I 100% copy pasted a code from the link below and I get the error below. I have installed all the dependencies required. I have used socket.io previously without problems, but never socket.io.users. The goal is to identify each PC as user.
var chatUsers = socketUsers.Users.of('/chat'); //
^
TypeError: Object #<Users> has no method 'of'
at Object.<anonymous> (/var/www/100moneta/components_not_larval/socket-user.js:16:35)
at Module._compile (module.js:456:26)
at Object.Module._extensions..js (module.js:474:10)
at Module.load (module.js:356:32)
at Function.Module._load (module.js:312:12)
at Function.Module.runMain (module.js:497:10)
at startup (node.js:119:16)
at node.js:902:3
My code:
var express = require('express');
var app = express();
var server = require('http').createServer(app);
var socketUsers = require('socket.io.users');
socketUsers.Session(app);//IMPORTANT
var rootIo = require('socket.io')(server); //default '/' as namespace.
var chatIo = rootIo.of('/chat');
var rootUsers = socketUsers.Users; /* default '/' as namespace. Each namespace has IT's OWN users object list,
but the Id of a user of any other namespace may has the same value if request comes from the same client-machine-user.
This makes easy to keep a kind of synchronization between all users of all different namespaces. */
var chatUsers = socketUsers.Users.of('/chat'); //
rootIo.use(socketUsers.Middleware());//IMPORTANT but no errors if you want to skip it for a io.of(namespace) that you don't want the socket.io.users' support.
chatUsers.use(socketUsers.Middleware());
chatUsers.on('connected',function(user){
console.log(user.id + ' has connected to the CHAT');
user.set('username', 'username setted by server side'); /*at the store property you can store any type of properties
and objects you want to share between your user's sockets. */
user.socket.on('any event', function(data){ //user.socket is the current socket, to get all connected sockets from this user, use: user.sockets
});
chatIo.emit('set username',user.get('username')); //or user.store.username
});
rootUsers.on('connected',function(user){
console.log('User has connected with ID: '+ user.id);
});
rootUsers.on('connection',function(user){
console.log('Socket ID: '+user.socket.id+' is user with ID: '+user.id);
});
rootUsers.on('disconnected',function(user){
console.log('User with ID: '+user.id+'is gone away :(');
});
//You can still use the io.on events, but the execution is after connected and connection of the 'users' and 'chatUsers', no matter the order.
rootIo.on('connection',function(socket){
console.log('IO DEBUG: Socket '+ socket.id+ ' is ready \n');
});
Link with the code and tutorial: https://www.npmjs.com/package/socket.io.users

Related

Loading the same native module into TWO node.js threads

I have a native C++ module that is spun up by a worker thread from node.js, which works great. From within that node module, I can call my native methods like "AddToLog()" and it works great.
I also need to service web requests, which is my dilemma. So I used express and included a file to start it up on a worker thread. That also works fine - both my native code and the express web server are working at the same time.
However, when I try to 'require' my native module in the file that starts the web server, I get an error that the native module could not be registered.
Have I hit a fundamental limitation where node.js cannot load the same native module on two different worker threads? Or this is as simple as a syntax issue?
My hunch is that I can fix this by making the module context aware, but I'm too new to this to know for sure!
I need the express thread to be able to access the module in order to draw its content. So one thread is running a lighting server that collects data and the other services web requests that describe the current state... if it worked!
// SCRIPT 1
'use strict'
const nightdriver = require('./build/Release/nightdriver.node')
const { Worker } = require('worker_threads');
function startserver()
{
nightdriver.addtolog("[index.js] Starting NightDriver Server");
//nightdriver.startserver();
}
const worker = new Worker("./startweb.js");
nightdriver.addtolog("[index.js] Starting Web Server...");
startserver();
// SCRIPT 2
'use strict'
const nightdriver = require('./build/Release/nightdriver.node')
var express = require('express');
var app = express();
app.get('/', function (req, res) {
res.send('Hello World');
})
var server = app.listen(8081, function () {
var host = server.address().address
var port = server.address().port
console.log("Example app listening at http://%s:%s", host, port)
})
events.js:167
throw er; // Unhandled 'error' event
^
Error: Module did not self-register.
at Object.Module._extensions..node (internal/modules/cjs/loader.js:736:18)
at Module.load (internal/modules/cjs/loader.js:605:32)
at tryModuleLoad (internal/modules/cjs/loader.js:544:12)
at Function.Module._load (internal/modules/cjs/loader.js:536:3)
at Module.require (internal/modules/cjs/loader.js:643:17)
at require (internal/modules/cjs/helpers.js:22:18)
at Object.<anonymous> (/Users/dave/OneDrive/Source/Node/nightdriver/startweb.js:2:21)
at Module._compile (internal/modules/cjs/loader.js:707:30)
at Object.Module._extensions..js (internal/modules/cjs/loader.js:718:10)
at Module.load (internal/modules/cjs/loader.js:605:32)
Emitted 'error' event at:
at Worker.[kOnErrorMessage] (internal/worker.js:332:10)
at Worker.[kOnMessage] (internal/worker.js:342:37)
at MessagePort.Worker.(anonymous function).on (internal/worker.js:279:57)
at MessagePort.emit (events.js:182:13)
at MessagePort.onmessage (internal/worker.js:84:8)

mongodb fails to connect even if i did exactly as the documentation

I am making an app using nodejs and I am learning the mongodb, but I do it just like the docs. but the command prompt shows:
events.js:141
throw er; // Unhandled 'error' event
^
Error: Trying to open unclosed connection.
at NativeConnection.Connection.open (C:\Users\html5col\Desktop\express\node_modules\mongoose\lib\connection.js:236:15)
at Mongoose.connect (C:\Users\html5col\Desktop\express\node_modules\mongoose\lib\index.js:241:47)
at Object.<anonymous> (C:\Users\html5col\Desktop\express\app.js:19:10)
at Module._compile (module.js:409:26)
at Object.Module._extensions..js (module.js:416:10)
at Module.load (module.js:343:32)
at Function.Module._load (module.js:300:12)
at Function.Module.runMain (module.js:441:10)
at startup (node.js:139:18)
at node.js:968:3
//my app.js file
var url = 'mongodb://fran84:fran#ds013250.mlab.com:13250/ndeme';
//ABOVE URL USING MLAB SERVICE
var mongoose = require('mongoose');
mongoose.connect(url);
console.log('isonerror');
var mydb = mongoose.connection;
console.log('ismydb');
mydb.on('error', console.error.bind(console, 'connection error:'));
mydb.once('open', function() {
// we're connected!
console.log('Connected to MongoDB');
var Schema = mongoose.Schema,
objectId = Schema.objectId;
var postSchema = mongoose.Schema({//With Mongoose, everything is derived from a Schema.
//id: objectId,//对象id
name: {type: String,default:20},
gender: {type: String,default:'male'},
// created_at: Date
}, { timestamps });
//add "speak" functionality to our documents:
postSchema.methods.speak = function(){
var greeting = this.name
? "His name is " + this.name
: "I do not have a nanme";
console.log(greeting);
}
//The next step is compiling our schema into a Model
var myModel = mongoose.model('try',postSchema);
var instance = new myModel({name:'roger',gender:'female'});
console.log(instance.name,instance.gender);
instance.save(function(err,instance){
if(err){
return console.error(err);
}
instance.speak();
});
//access all of the kitten documents through our myModel model.
myModel.find(function(err,tries){
if(err){return console.error(err)}
console.log(tries);
});
});
MORE:
ACCORDING DOCS:http://mongoosejs.com/docs/index.html
ADD 2:
It seems that when I deletes the content of the mydb.once's callback function, it still shows the same problem.
You are trying to create another connection without closing the current one. you should use
createConnection() instead of connect().
It would look like:-
db = mongoose.createConnection(url);
Some sample linls for your help,
Why am I getting error "Trying to open unclosed connection."?
Mongoose Trying to open unclosed connection
The error is implying that you have already connected once in your application. Trying to connect again will throw the exception you're seeing.

Missing PFX or certificate + private key

I have set the keys to node.js but still i am unable to get it to working.
Can anybody tell me what should i do to make it work properly.
I need to work with https with node.js.
I get the following error.
`tls.js:1127
throw new Error('Missing PFX or certificate + private key.');
^
Error: Missing PFX or certificate + private key.
at Server (tls.js:1127:11)
at new Server (https.js:35:14)
at Object.exports.createServer (https.js:54:10)
at Object.<anonymous> (/var/www/html/fusionmate/nodejs/server.js:4:36)
at Module._compile (module.js:456:26)
at Object.Module._extensions..js (module.js:474:10)
at Module.load (module.js:356:32)
at Function.Module._load (module.js:312:12)
at Function.Module.runMain (module.js:497:10)
at startup (node.js:119:16)`
Hers my code
var
app = require('https').createServer(handler),
io = require('socket.io')(app),
redis = require('redis'),
fs = require('fs'),
redisClient = redis.createClient();
var options = {
key: fs.readFileSync('/etc/apache2/ssl/apache.key'),
cert: fs.readFileSync('/etc/apache2/ssl/apache.crt')
};
app.createServer(options);
app.listen(3000);
console.log('Realtime Chat Server running at http://127.0.0.1:3000/');
function handler (req, res) {
fs.readFile(__dirname + '/index.html', function(err, data) {
if(err) {
res.writeHead(500);
return res.end('Error loading index.html');
}
res.writeHead(200);
res.end(data);
});
}
There are two issues here:
options needs to be passed to https.createServer() as the first argument (with handler being the optional second argument), but you're just passing in a request handler function. For example:
var fs = require('fs');
var options = {
key: fs.readFileSync('/etc/apache2/ssl/apache.key'),
cert: fs.readFileSync('/etc/apache2/ssl/apache.crt')
};
var app = require('https').createServer(options, handler);
// ...
Further down, you're calling createServer() on an https.Server (app) instance, which isn't correct (you've already created a server instance and instances don't have such a method).

Load Balancer for NodeJS Net Server

I have a following NodeJS server file that is supposed to handle following JSON Message:
If received message as key, send some response.
If received app as key, send some DLL to the client.
Now I am interested in handling multiple clients that will, for this case, send only message as Key in JSON.
Here is the code:
var net = require('net');
var fs = require('fs');
var util = require('util');
var server = net.createServer(function(c) { //'connection' listener
console.log('client connected');
c.on('end', function() {
console.log('client disconnected');
});
c.on('data', function(data) {
var json = JSON.parse(data.toString());
if(json.heartbeat){
if(json.first_fetch === "1"){
c.write("{\"config_changed\":\"true\",\"config\":\"This is some config\"}"); // JSON Message here
}
else{
c.write("{\"config_changed\":\"false\"}");
}
}
else if(json.message){
c.write("{\"success\":\"true\"}");
}
else if(json.app){
fs.exists('apps/'+ json.app + ".dll", function (exists) {
util.debug(exists ? "it's there" : "Its not there");
});
var stats = fs.statSync('apps/'+ json.app + ".dll")
var fileSizeInBytes = stats["size"]
var message = json.app + "\n" + fileSizeInBytes + "\n";
c.write(message);
fs.open('apps/'+ json.app + ".dll","r", function(status, fd){
console.log(fd);
var read_bytes = 0;
var fileStream = fs.createReadStream('apps/'+ json.app + ".dll");
fileStream.on('data',function(chunk){
c.write(chunk);
});
})
}
else
{
c.write("{\"some\":\"error\"}");
}
});
c.on('error', function (e) {
console.log(e);
});
// c.pipe(c);
});
server.listen(1936, function() { //'listening' listener
console.log('server bound');
});
My client will send message as {"message":"This is message"}, and server will send {"success":"true"}. I received following benchmark of the server I created:
One client sent 200000 message in 7 seconds.
Two clients, each sent message in 13/14 seconds.
Three clients, each sent message in 17/17/16 seconds.
The time for each client reduces significantly when they are sending message to one server. I tried to run multiple server at once, but it gave:
events.js:85
throw er; // Unhandled 'error' event
^
Error: listen EADDRINUSE
at exports._errnoException (util.js:746:11)
at Server._listen2 (net.js:1156:14)
at listen (net.js:1182:10)
at Server.listen (net.js:1267:5)
at Object.<anonymous> (C:\Users\Dell\Desktop\nodeserver\server.js:54:8)
at Module._compile (module.js:460:26)
at Object.Module._extensions..js (module.js:478:10)
at Module.load (module.js:355:32)
at Function.Module._load (module.js:310:12)
at Function.Module.runMain (module.js:501:10)
If I want to get the performance of 200K in 7 seconds for each of clients, how am I to proceed. I want to run multiple instance of servers, with a load balancer to improve the server efficiency. I am using Windows.
try to use node.js Cluster module for this
https://nodejs.org/api/cluster.html
different nodejs instances can't share same port
another approach is to use external load balancer, nginx for example
http://nginx.org/en/docs/http/load_balancing.html

I create a node app that is working locally. I need help to modify server.js so that it can work on heroku

I create a node app that is working locally. I need help to modify server.js below so that it can work on heroku.
server.js:
var http = require('http');
var session = require('cookie-session');
var port = 9500;
var Assets = require('./backend/Assets');
var API = require('./backend/API');
var Default = require('./backend/Default');
var Chat = require('./backend/Chat');
var Router = require('./frontend/js/lib/router')();
Router
.add('static', Assets)
.add('node_modules', Assets)
.add('tests', Assets)
.add('api', API)
.add(Default);
var checkSession = function(req, res) {
session({
keys: ['nodejs-by-example']
})(req, res, function() {
process(req, res);
});
}
var process = function(req, res) {
Router.check(req.url, [req, res]);
}
var app = http.createServer(checkSession).listen(port, '127.0.0.1');
console.log("Listening on 127.0.0.1:" + port);
Chat(app);
I tried:
var port = Number(process.env.PORT || 9000);
But it didn't work. I got this error:
users-MacBook-Pro-6:project user$ node server
/Users/user/Desktop/project/server.js:3
var port = Number(process.env.PORT || 5000);
TypeError: Cannot read property 'env' of undefined
at Object.<anonymous> (/Users/user/Desktop/project/server.js:3:26)
at Module._compile (module.js:456:26)
at Object.Module._extensions..js (module.js:474:10)
at Module.load (module.js:356:32)
at Function.Module._load (module.js:312:12)
at Function.Module.runMain (module.js:497:10)
at startup (node.js:119:16)
at node.js:906:3
It looks like you are getting an undefined process variable. To troubleshoot you should do a console.dir(process) which will print out everything on the process variable including your environment variables.
As well you can try doing this - heroku config:set NODE_ENV=production per heroku support
Could possibly be related to this.
Update
To further troubleshoot you will need to install a logging addon-
heroku addons:create papertrail
After you install you will be able to navigate to the add-on and see any messages that are being logged related to the deployment as well as your console.dir and console.log printouts.

Resources