Empresas
Empleos
  • Sobre nosotros
  • Soluciones
    • Publicación de vacantes
      Publica tu vacante y recibe candidatos calificados en 48h.
    • Evaluación de candidatos
      500+ pruebas técnicas y psicológicas, más anti-fraude.
    • Headhunting
      Búsqueda ejecutiva a la medida de principio a fin.
    • Nómina + EOR
      Dispersión de nómina y EOR en más de 15 países de LATAM.
  • Precios
  • Empleos

0

430
Vistas
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 Respuestas
Responde la pregunta

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 Denunciar
Responde la pregunta
Encuentra empleos remotos

¡Descubre la nueva forma de encontrar empleo!

Top de empleos
Top categorías de empleo
Empresas
Publicar vacante Precios Comercial
Legal
Términos y condiciones Política de privacidad
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomiéndame algunas ofertas
Necesito ayuda