How can I get socket.io to work with deno?

4k views Asked by At

My aim is to get socket.io to work with deno. Deno does have a standard library for web sockets, but that does not have a fail-over. I think it is possible to use the UNPKG service to use an NPM package in you deno program, but I seem to get the syntax wrong for importing socket.io:

import { serve } from "https://deno.land/std/http/server.ts";
import {Socket} from "https://unpkg.com/browse/[email protected]/dist/index.d.ts";

new Worker(new URL("worker.js", import.meta.url).href, { type: "module" });
const server = serve({ port: 3001 });
const app = new Application();
const io = Socket(3001);

// serve index page
if (req.url === "/") {
  req.respond({
    status: 200,
    body: await Deno.open("./public/index.html"),
  });
}

io.on("connection", (socket) => {
  // either with send()
  socket.send("Hello!");

  // or with emit() and custom event names
  socket.emit("greetings", "Hey!", { "ms": "jane" }, Buffer.from([4, 3, 3, 1]));

  // handle the event sent with socket.send()
  socket.on("message", (data) => {
    console.log(data);
  });

  // handle the event sent with socket.emit()
  socket.on("salutations", (elem1, elem2, elem3) => {
    console.log(elem1, elem2, elem3);
  });
});

I get the following error:

error: An unsupported media type was attempted to be imported as a module.
  Specifier: https://unpkg.com/browse/[email protected]/dist/index.d.ts
  MediaType: Unknown
2

There are 2 answers

0
Indecisive On

It fails because you are importing a .d.ts file, which is a declaration file and essentially you can't run any code from - it's purely to support types.

Instead you should replace index.d.ts with index.js

0
hong4rc On

Try this:

import Socket from 'https://cdn.esm.sh/v9/[email protected]/esnext/socket.io.js';

As @Indecisive said, you are importing a .d.ts file.

You can use @Marcos Casagrande: https://stackoverflow.com/a/61821141/6250402 (remember install socket.io module with npm)

Or use https://deno.land/[email protected]/ws/mod.ts