Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

340
Visualizações
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!

about 4 years ago · Juan Pablo Isaza
Responde à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda