L
L
LAMbl42018-07-14 02:06:58
MongoDB
LAMbl4, 2018-07-14 02:06:58

How to properly link socket.io Node.js modules?

2 functions are performed on the server: 1.
Receiving a user (stored in the database)
2. Creating a marker by the user (stored in the database and transmitted over the socket)
work synchronously i.e. the response from the database does not have time to arrive, and the server is already sending the response

//app.js
var app = require('express')();
var server = require('http').Server(app);
var io = require('socket.io')(server);
var db = require('./db');
var User = require('./user/UserController');

server.listen(8080);

app.get('/', function (req, res) {
  res.sendfile(__dirname + '/page/index.html');
});

io.on('connection', function (socket) {
  console.log('connect user:' + socket.id);
  
  socket.on('GetUser', function (id) {
    socket.emit('SendUser',  User.Get(id));
    })
  })
  
  socket.on('disconnect', function () {
  io.emit('user disconnected');
    console.log('disconnect user:' + socket.id);
  });
});

// UserController.js
var express = require('express');
var router = express.Router();
var User = require('./User');

// GETS A SINGLE USER FROM THE DATABASE
var UserController = {
  Get : function (fb_id) {
    User.findOne(fb_id , function (err, user) {
      var res
      
      if (err) res = JSON.stringify({ success: 'false', message: 'There was a problem finding the user.' });
      else if (!user) res = JSON.stringify({ success: 'false', message: 'No user found.' });
      else res = JSON.stringify({ success: 'true', message: 'return user.', result: user });

      return res;
    })
  }
}

module.exports =  UserController;

Answer the question

In order to leave comments, you need to log in

1 answer(s)
A
Alino4ka, 2018-07-14
@Alino4ka

async/await or callback and use it to send a message to socket.io

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question