Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

429
Views
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 answers
Answer question

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 Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!