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

431
Visualizações
How to get socket.io working with ES6 import modules?

I refactored a simple example of socket.io from CommonJS require syntax to ES6 import syntax but when I start the server and go to the website, although it shows the HTML text ("test from server.js"), it doesn't inform the server that it is connected.

Yet there are no errors in the console at all, it just acts as if socket.io is not loading at all.

In my package.json file, I have the following entry in order that ES6 modules work in Node:

"type": "module",

Why is socket.io not working?

server.js

import path from 'path';
import http from 'http';
import express from 'express';
import { Server as socketIO } from 'socket.io';

const app = express();
const PORT = 5011;
const __dirname = path.resolve(path.dirname(''));
const server = http.Server(app);
const io = new socketIO(server);

app.get('/', (req, res) => {
    res.sendFile(__dirname + '/public/index.html');
});

io.on('connection', (socket) => {
    console.log('user connected');
    socket.emit('greeting-from-server', {
        greeting: 'you loaded the page'
    });
})

app.listen(PORT, () => {
    console.log(`listening on port http://localhost:${PORT}`);
});

/public/index.html

<html lang="en">

<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible"
          content="IE=edge">
    <meta name="viewport"
          content="width=device-width, initial-scale=1.0">
    <title>Socket.IO</title>
    <script src="/socket.io/socket.io.js"></script>
    <script>
        const socket = io('http://localhost:5011');
        socket.on('greeting-from-server', (data) => {
            console.log(data);
            socket.emit('greeting-from-client', {
                greeting: 'Hello Server'
            });
        });
    </script>
</head>

<body>
    test from server.js
</body>

</html>
about 4 years ago · Juan Pablo Isaza
1 Respostas
Responde à pergunta

0

import { createServer } from "http";
import { Server } from "socket.io";

const httpServer = createServer();
const io = new Server(httpServer, {
  // ...
});

io.on("connection", (socket) => {
  // ...
});enter code here

httpServer.listen(3000);
about 4 years ago · Juan Pablo Isaza Relatório
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