0
votes

We are complete newbies to socket.io and express. And we have followed along this tutorial to learn socket.io https://www.valentinog.com/blog/socket-react/

And now we want to translate this line of code (older style):

const index = require("./routes/index").default

to ES6, below:

import router from './routes/index'

app.use('/', router)

But it does not work for us. We get this error in the terminal. error

Full server.js code here

import express from 'express'
const app = express()
import { createServer } from 'http'
const server = createServer(app)
import { Server } from "socket.io"
const io = new Server(server)
import cors from 'cors'

import router from './routes/index' 

const port = process.env.PORT || 4001

app.use('/', router)

app.use(index)

app.use(cors())
app.use(express.json())

let interval

io.on("connection", (socket) => {
  console.log("New client connected")
  if (interval) {
    clearInterval(interval)
  } 
  interval = setInterval(() => getApiAndEmit(socket), 1000)
  socket.on("disconnect", () => {
    console.log("Client disconnected")
    clearInterval(interval)
  })
})

const getApiAndEmit = socket => {
  const response = new Date()

  socket.emit("FromAPI", response)
}

app.listen(port, () => {
  // eslint-disable-next-line
  console.log(`Server running on http://localhost:${port}`)
})

1
You will probably have to modify how you export the routes. In your routes/index file, try replacing module.exports = router; by export default router; - Gaëtan Boyals
Thanks, but we already did that. - Caroline
In that case, please double-check the path, and try adding the extension of the file when importing the file. - Gaëtan Boyals
It's the extension (or lack thereof). You need to provide full file extensions with ESM. import router from './routes/index.js'. The error message even tells you this. - rschristian

1 Answers

0
votes

I was able to use socket.io on my project like so:

const app = express()
const http = require('http').createServer(app)
const socketIo = require('socket.io')(http)

In other words I used require and did not use router. This might work for you unless there is a specific reason you need to do otherwise.