Company logo
  • Empleos
  • Bootcamp
  • Acerca de nosotros
  • Para profesionales
    • Inicio
    • Empleos
    • Cursos y retos
    • Preguntas
    • Profesores
    • Bootcamp
  • Para empresas
    • Inicio
    • Nuestro proceso
    • Planes
    • Pruebas
    • Nómina
    • Blog
    • Comercial
    • Calculadora

0

122
Vistas
Best method of sharing classes between node server and browser frontend? (socket.io)

I'm just getting into client/server architecture and am not sure if there is a best practice for this. I have a file structure as follows:

.
|-public
|  |-index.html
|  |-client.js
|  |-src
|  |  |-person.js
|-server.js

person.js is a class that I would like to share between the server and the client. socket.io lets me send over a json object, but I cannot find a way to send methods attached to a Person(). So instead, I'm resorting to sending over a json and reinitializing the Person object. This also leads me to some import issues.

On server.js:

const { Person } = require('./public/src/person')
...

io.on('connection', client => client.emit('init', new Person({data}))

On client.js:

let person;
socket.on('init', handlePerson);
function handlePerson(data) {
    person = new Person(data);
    person.method();
    ...
}

While this works, I'm wondering if there's a better way to do it. It's also forcing me to put an ugly export at the bottom of person.js:

if (typeof module !== 'undefined') {
    module.exports = {
        Overworld
    }
}

where the server requires the inner module.exports, but the client would get Uncaught ReferenceError: module is not defined

I should add, my index.html is importing the js files like so:

<script src="/socket.io/socket.io.js"></script>
<script src="/src/Overworld.js"></script>
<script src="/client.js"></script>

I think one of these files must be seriously cringe for an experienced js developer. Any help or explanation would be appreciated!

7 months ago · Juan Pablo Isaza
Responde la pregunta
Encuentra empleos remotos