將 socket.io 從 v3 升級到 v4

將 socket.io 從 v2 升級到 v3 之後,本文是關於將 socket.io 及其相關軟體包升級到撰寫本文時的最新版本,唯一的設定變更似乎是來自 redis-adapater 和使用針對我們的特定方式(導入客戶端)。

Upgrade guide

Basically read the Migrating from 3.x to 4.0 official guide, then:

  • For npm packages
-   "socket.io": "3.1.2",
-   "socket.io-emitter": "3.2.0",
-   "socket.io-redis": "6.0.1",

+   "socket.io": "4.4.1",
+   "@socket.io/redis-emitter": "4.1.1",
+   "@socket.io/redis-adapter": "7.1.0",
  • For redis-adapter config
    The adapter has changed method signatures about the redis pubClient and subClient, see this issues/411 for details.
- this.io.adapter(
-  createAdapter({
-    pubClient,
-    subClient,
-  }),
- );

+ this.io.adapter(
+  createAdapter(pubClient, subClient),
+ );
  • For client (if any)
    The way to import the io function is changed:
- const io = require('socket.io-client');

+ const { io } = require('socket.io-client');

參考文獻

javascript socket.io nodejs