by Hugo
雨果
使用Chatkit構建Node.js命令行聊天應用程序 (Build a Node.js command-line chat application with Chatkit)
Building chat in your app can be pretty complex. Yet, with Chatkit, implementing fully-featured chat is nothing but a few lines of code.
在您的應用中建立聊天可能非常復雜。 但是,使用Chatkit ,實現功能齊全的聊天只不過是幾行代碼。
In this tutorial, I’ll walk you through how to build a command-line chat, like this:
在本教程中,我將指導您如何建立命令行聊天,如下所示:
The complete code can be found on GitHub.
完整的代碼可以在GitHub上找到 。
什么是Chatkit? (What is Chatkit?)
You might be wondering, “what is Chatkit?”
您可能會想,“什么是Chatkit?”
In a nutshell, Chatkit is an API to help you build chat functionality in your app. Functionality like:
簡而言之,Chatkit是一個API,可幫助您在應用程序中構建聊天功能。 功能類似:
- Rooms 房間數
- Online presence 在線存在
- Typing indicators 打字指標
- Read indicators (unread message count, read receipts) 閱讀指示器(未讀郵件數,已讀回執)
- Rich media messages 富媒體消息
- And more 和更多
Additionally, Chatkit handles tricky details that come up when building real-time chat like reliability, and scale.
此外,Chatkit處理構建實時聊天時出現的棘手細節,例如可靠性和規模。
To me, using Chatkit means not having to deal with rolling a web socket server, managing infrastructure for it, and dealing with managing chat at scale!
對我來說,使用Chatkit意味著不必處理滾動Web套接字服務器,管理該服務器的基礎結構以及處理大規模聊天的問題!
In this tutorial, we’ll only touch the surface of what Chatkit can do. To give you an idea of what you can build, check out this open source Slack clone, powered by Chatkit:
在本教程中,我們僅涉及Chatkit可以做的事情。 為了讓您大致了解可以構建的內容,請查看由Chatkit支持的開源Slack克隆:
Pretty neat, right?
很整潔吧?
創建一個Chatkit實例 (Create a Chatkit instance)
Before diving into the tutorial, you should setup a Chatkit instance. It only takes a second.
在開始學習本教程之前,您應該設置一個Chatkit實例。 只需要一秒鐘。
To create one, head to pusher.com/chatkit and click Sign Up. Within the dashboard, beneath “Chatkit”, hit Create new + then enter a name for the instance. I called mine “My Awesome Chatkit App!”:
要創建一個,請訪問pusher.com/chatkit并單擊“ 注冊” 。 在儀表板內的“ Chatkit”下,單擊“ 創建新+ ”,然后輸入實例的名稱。 我稱我為“我的超贊聊天工具應用!”:
Within the Keys tab, take note of your Instance Locator and Secret Key. We’ll need these in a moment.
在“ 密鑰”選項卡中,記下您的Instance Locator和Secret Key 。 我們稍后將需要這些。
創建聊天室 (Create a Chatkit room)
Chatkit enables us to create public or private chat rooms, and even supports one-to-one chat.
Chatkit使我們能夠創建公共或私人聊天室,甚至支持一對一聊天。
Normally, you’d create rooms dynamically — for example, when an end user creates a new room—but in this tutorial we’ll the Inspector to create one manually:
通常,您會動態創建房間(例如,當最終用戶創建新房間時),但是在本教程中,我們將由檢查員手動創建一個房間:
創建身份驗證服務器 (Create an authentication server)
Authentication is the action of proving a user is who they say they are. Normally, this involves a password.
身份驗證是證明用戶就是他們所說的身份的行為。 通常,這涉及一個密碼。
In this tutorial, we won’t authenticate users —we won’t ask them for a password — but we’ll still need to write an /authenticate
route that returns a Chatkit token.
在本教程中,我們不會對用戶進行身份驗證-我們不會要求他們提供密碼-但我們仍然需要編寫/authenticate
路由來返回Chatkit令牌 。
Additionally, we’ll need to define a route called /users
that creates a Chatkit user.
此外,我們需要定義一個名為/users
的路由,以創建一個Chatkit用戶。
To do this, create a new folder, I called mine terminal-chat
. Then, install @pusher-chatkit-server
, express
, and some Express middleware:
為此,請創建一個新文件夾,我稱為mine terminal-chat
。 然后,安裝@pusher-chatkit-server
, express
和一些Express中間件:
mkdir terminal-chat
cd terminal-chat
npm init -y
npm install --save @pusher/chatkit-server npm install --save express npm install --save body-parser cors
Then, create a new file called server.js
and paste in the following code:
然后,創建一個名為server.js
的新文件,并粘貼以下代碼:
Remember to replace YOUR_INSTANCE_LOCATOR
and YOUR_CHATKIT_KEY
with your own.
請記住用自己的替換YOUR_INSTANCE_LOCATOR
和YOUR_CHATKIT_KEY
。
設置我們的客戶 (Setup our client)
Now we have a server and a Chatkit instance, we can start building the command-line client.
現在我們有了服務器和Chatkit實例,我們可以開始構建命令行客戶端了。
In the same project, install @pusher/chatkit
and jsdom
:
在同一項目中,安裝@pusher/chatkit
和jsdom
:
npm install --save @pusher/chatkitnpm install --save jsdom
To be clear, in the previous step, we installed the Chatkit server SDK (@pusher/chatkit-server
) and here, we install the client Chatkit SDK (@pusher/chatkit-client
). We also installed jsdom
, but more on that in a moment.
為了清楚起見,在上一步中,我們安裝了Chatkit 服務器 SDK( @pusher/chatkit-server
),在這里,我們安裝了客戶端 Chatkit SDK( @pusher/chatkit-client
)。 我們還安裝了jsdom
,但jsdom
更多介紹。
In a new file called client.js
, paste the following:
在名為client.js
的新文件中,粘貼以下內容:
Starting at the top, we first import ChatManager
and TokenProvider
from @pusher/chatkit
. We’ll reference these soon.
從頂部開始,我們首先從@pusher/chatkit
導入ChatManager
和TokenProvider
。 我們將盡快參考這些內容。
We also import jsdom
, the dependency I mentioned earlier.
我們還導入了前面提到的jsdom
。
In a nutshell, @pusher/chatkit-client
works in the browser but not in Node. In a function called makeChatkitNodeCompatible
, we use jsdom
to “trick” Chatkit into thinking it’s running in the browser ?. This is a temporary workaround, but it works perfectly.
簡而言之, @pusher/chatkit-client
在瀏覽器中有效,而在Node中不起作用。 在一個名為makeChatkitNodeCompatible
的函數中,我們使用jsdom
來“欺騙” Chatkit,使其認為它正在瀏覽器中運行? 這是在應急解決方法上,但它可以完美運行。
At the bottom of the module, we define an async
function called main
, which enables us to use await
when calling asynchronous functions.
在模塊的底部,我們定義了一個名為main
的async
函數,該函數使我們能夠在調用異步函數時使用await
。
If await
is a new concept to you, here’s a great introduction.
如果對您來說await
是一個新概念,這是一個很棒的介紹 。
提示用戶輸入用戶名 (Prompt the user for their username)
Before we can allow a user to join a room, we need prompt them for their name. To do this, we can use prompt.
在允許用戶加入房間之前,我們需要提示他們輸入名稱。 為此,我們可以使用prompt.
First, install prompt
:
首先,安裝prompt
:
npm install --save prompt
And then, import it:
然后導入:
Then, update our main function:
然后,更新我們的主要功能:
Now, if we run the app with the command node client.js
, we should have our prompt:
現在,如果使用命令node client.js
運行該應用程序,則應顯示提示:
Woo ?!
??!
創建一個用戶 (Create a user)
Before connecting to Chatkit, we must first create a Chatkit user via the server we wrote earlier.
連接到Chatkit之前,我們必須首先通過我們先前編寫的服務器創建一個Chatkit用戶。
To do this, we’ll send a request to the /users
route using axios
, which is a HTTP client:
為此,我們將使用axios
將請求發送到/users
路由, axios
是HTTP客戶端:
npm install --save axios
After installing axios
, import it:
安裝axios
,將其導入:
Then, define a function called createUser
:
然后,定義一個名為createUser
的函數:
We can now call this function with the prompted username:
現在,我們可以使用提示的用戶名調用此函數:
Let’s test this out.
讓我們測試一下。
Open two terminal windows. In one, start the server with node server.js
and in the other, run the client with node client.js
. If all is well, you should be prompted for a username, and you’ll see User created: <userna
me> in the server output.
打開兩個終端窗口。 一種是使用node server.js
啟動服務器,另一種是使用node client.js
運行客戶node client.js
。 如果一切正常, 則系統將提示您輸入用戶名,并且服務器輸出User created: <userna
me>。
If you see an error along the lines of Failed to create a user, connect ECONNREFUSED
then your server might not be running, so double check that.
如果Failed to create a user, connect ECONNREFUSED
的行中看到錯誤Failed to create a user, connect ECONNREFUSED
則您的服務器可能未運行,因此請仔細檢查。
設置Chatkit SDK (Setup the Chatkit SDK)
At this point, we have a username and the ability to create a user. Next, we’ll want to connect to Chatkit as that user.
至此,我們有了用戶名和創建用戶的能力。 接下來,我們要以該用戶身份連接到Chatkit。
To do this, beneath the call you just made to createUser
, paste the following:
為此,在您剛剛對createUser
進行的調用下面,粘貼以下內容:
Again, remember to replace your YOUR_INSTANCE_LOCATOR
with the Instance Locator you noted earlier.
同樣,請記住將您的YOUR_INSTANCE_LOCATOR
替換為您之前提到的實例定位器 。
This code initialises Chatkit then connects to the service, returning the currentUser
. Note how we provide a TokenProvider
which points to our authentication server.
此代碼初始化Chatkit,然后連接到服務,并返回currentUser
。 請注意,我們如何提供指向我們的身份驗證服務器的TokenProvider
。
上市房 (Listing rooms)
Now we have an authenticated user, we can show them a list of rooms they can join.
現在我們有了一個經過身份驗證的用戶,我們可以向他們顯示他們可以加入的房間的列表。
To do this, we should update the main function in client.js
to fetch joinable rooms (getJoinableRooms
), and list them alongside the rooms a user has already joined (user.rooms
):
要做到這一點,我們應該更新的主要功能client.js
獲取可連接室( getJoinableRooms
),并列出他們旁邊的房間用戶已經加入( user.rooms
):
The ...
syntax there is called destructuring, and it provides a succinct way to merge two or more arrays.
那里的...
語法稱為destructuring ,它提供了合并兩個或更多數組的簡潔方法。
Running node client.js
should now print out a list of rooms:
運行node client.js
現在應該打印出房間列表:
You’ll probably just see one room to start with. To create additional rooms, go back to the Inspector or use the the createRoom
function.
您可能只會看到一個房間開始。 要創建其他房間,請返回檢查器或使用createRoom
功能。
訂閱房間 (Subscribe to a room)
Next, we should prompt the user to pick a room, with this code:
接下來,我們應使用以下代碼提示用戶選擇房間:
One cool thing about prompt
is that you can create validation rules. Above, we create one to make sure the user’s input is between 0
and the number of joinable rooms.
關于prompt
一件很酷的事情是,您可以創建驗證規則。 在上面,我們創建一個以確保用戶輸入的值在0
到可連接房間的數量之間。
Once we have the user’s room choice, we can set that as the room
and subscribe to the room:
選擇了用戶的房間后,我們可以將其設置為room
并訂閱該房間:
Upon subscribing, we add a onNewMessage
hook.
訂閱后,我們添加了onNewMessage
鉤子 。
You can think of a hook as a function that is called whenever an event occurs. In this case it’s when a new message is received.
您可以將鉤子視為事件發生時調用的函數。 在這種情況下,就是收到新消息的時候。
onNewMessage
will be called in real-time whenever a new message is sent by “a user”. When I say “a user”, that includes the current user, so within the function we only print the message if it was sent by someone else.
每當“用戶”發送新消息時,就會實時調用onNewMessage
。 當我說“用戶”時,其中包括當前用戶,因此在此功能中,我們僅在消息是由其他人發送的情況下打印消息。
通過用戶輸入發送消息 (Send messages from user input)
Being able to receive messages isn’t much use if we can’t also send messages now, is it?
如果我們現在也不能發送消息,那么能夠接收消息的用處不大,不是嗎?
Fortunately, sending a message is but one line of code with Chatkit.
幸運的是,使用Chatkit發送消息只是一行代碼。
First, install readline
to read input from the user:
首先,安裝readline
以讀取用戶的輸入:
npm install --save readline
Then, import it:
然后,將其導入:
Finally, reference it below:
最后,在下面引用它:
If you run two instances of the client, you should be able to send and receive messages:
如果運行客戶端的兩個實例,則應該能夠發送和接收消息:
添加一個加載微調器,讓它很有趣? (Add a loading spinner for a bit of fun ?)
As ever, sending data over the network might take a second or two. For a bit of fun, and to make our application feel faster, let’s add a nifty loading spinner:
與以往一樣,通過網絡發送數據可能需要一到兩秒鐘。 對于一點樂趣,并且使我們的應用程序的感覺速度更快,讓我們添加一個漂亮的加載微調:
First, install ora
, a loading spinner module:
首先,安裝ora
,它是一個加載微調器模塊:
npm install --save ora
Then, in client.js
,we can call start
, succeed
, etc. depending on the status of the command.
然后,在client.js
,我們可以根據命令的狀態調用start
, succeed
等。
Here’s the complete client.js
file, with the new spinner-related code highlighted:
這是完整的client.js
文件,其中突出顯示了與微調框相關的新代碼:
結論 (Conclusion)
Amazing, we’re done!
太神奇了,我們完成了!
To recap, you learned how to:
回顧一下,您學習了如何:
- Prompt and authenticate the user 提示并驗證用戶
- Connect to Chatkit 連接到聊天包
- List the users available rooms 列出用戶可用的房間
- Join a room 加入房間
- Send and receive messages from a room 在會議室發送和接收消息
- And, for fun, add a loading spinner 并且,為了娛樂,添加一個加載微調器
In this tutorial, we barely touched the surface of Chatkit. There’s so much more we could build, including:
在本教程中,我們幾乎沒有觸及Chatkit的表面。 我們可以建立更多的東西,包括:
- Switch between rooms 在房間之間切換
- Create new rooms 建立新房間
- Show users offline/offline status 顯示用戶離線/離線狀態
- Show typing indicators 顯示打字指示
- Show read receipts 顯示已讀回執
Want to learn how? Let me know in the comments and we’ll write part 2.
想學習如何? 在評論中讓我知道,我們將編寫第2部分。
Alex Booker created a video tutorial based on this article. Check it out!
Alex Booker根據本文創建了一個視頻教程。 看看這個!
翻譯自: https://www.freecodecamp.org/news/build-a-node-js-command-line-chat-application-with-chatkit-8d0c4546085e/