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 LocatorSecret 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-serverexpress和一些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_LOCATORYOUR_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/chatkitjsdom

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导入ChatManagerTokenProvider 。 我们将尽快参考这些内容。

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.

在模块的底部,我们定义了一个名为mainasync函数,该函数使我们能够在调用异步函数时使用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: <username> 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 ,我们可以根据命令的状态调用startsucceed等。

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/

使用Chatkit构建Node.js命令行聊天应用程序相关推荐

  1. 怎样开发一个 Node.js 命令行工具包

    大家好,我是若川.最近组织了源码共读活动,感兴趣的可以点此加我微信 ruochuan12 参与,每周大家一起学习200行左右的源码,共同进步.同时极力推荐订阅我写的<学习源码整体架构系列> ...

  2. node.js命令行程序在Windows系统和Linux系统下的部署

    在Windows系统下全局部署node.js写的命令行程序 我们有一个简单的命令行程序,使用node.js的commander模块写的,只有一个文件hello.js,其内容如下: #!/usr/bin ...

  3. 01.Node.JS 命令行窗口

    1.命令行窗口/(小黑屏)/CMD窗口/ 终端/ shell a,-开始菜单-运行-CMD-回车  b,-windows键+R --常用的指令: dir:列出当前目录所有文件 cd+目录名:进入指定目 ...

  4. 跟着老司机玩转Node自定义命令行

    看之前熟读已下文章: 跟着老司机玩转Node命令行 Nodejs 制作命令行工具 github.com/jaywcjlove/- node生成自定义命令(yargs/commander) 通过node ...

  5. 构建node.js基础镜像_在Android上构建Node.js应用程序

    构建node.js基础镜像 by Aurélien Giraud 通过AurélienGiraud 在Android上构建Node.js应用程序-第1部分:Termux,Vim和Node.js (Bu ...

  6. 如何在Docker上构建Node.js应用程序

    Docker has been the latest trending topic over the past couple of years and if you haven't been to s ...

  7. 构建node.js基础镜像_我如何使用Node.js构建工作抓取网络应用

    构建node.js基础镜像 by Oyetoke Tobi Emmanuel 由Oyetoke Tobi Emmanuel 我如何使用Node.js构建工作抓取网络应用 (How I built a ...

  8. node 使用命令行运行esm脚本

    原文链接: node 使用命令行运行esm脚本 上一篇: fp-ts 简单瞅瞅 下一篇: js 简单卡通滤镜 https://www.npmjs.com/package/esm 主要是在scripts ...

  9. 局域网下C++命令行聊天室简易版

    利用C++在Linux环境下写了一个简单的命令行聊天服务器.主要用到的技术是socket,I/O复用(epoll),非阻塞IO,进程等知识.下面主要叙述其中的关键技术点以及编写过程中遇到的问题. 0. ...

最新文章

  1. Android面试常问到的知识点
  2. ecshop简单三部实现导航分类二级菜单
  3. 【Android视图效果】共享元素实现仿微信查看大图效果
  4. android 起动APP时锁住(Lock apps)
  5. PHP 7.2 新功能介绍
  6. [译]ASP.NET Core Web API 中使用Oracle数据库和Dapper看这篇就够了
  7. 3部世界顶级宇宙纪录片,献给对宇宙万物充满好奇的你
  8. JavaScript学习随记——常见全局对象属性及方法
  9. Centos7 网络报错Job for iptables.service failed because the control process exited with error code....
  10. Fiddler环境配置教程
  11. vm16安装efi win7 方案
  12. Visual studio 无法打开源文件的问题或系统找不到指定文件
  13. python运维小工具_Python实现跨平台运维小神器
  14. ASUS华硕天选2 FX506H INTELI711代CPU 原装出厂系统恢复原厂系统
  15. win10更新后D盘变成CD驱动器
  16. 芒果改进YOLOv7系列:超越ConvNeXt结构,原创结合Conv2Former改进结构,Transformer 风格的卷积网络视觉基线模型,高效涨点
  17. 常用的几种 GPRS 模块
  18. PSPICE混沌电路的相图操作
  19. instagram分析以预测与安的限量版运动鞋转售价格
  20. Python学习教程:数据类型—字符串大总结

热门文章

  1. 丁香园 武汉 神童_杭州、武汉、成都哪个城市更适合程序员发展
  2. 关于LaaS,PaaS,SaaS一些个人的理解
  3. vue之axios 登陆验证及数据获取
  4. DRUID连接池的简单使用
  5. jQuery Mobile 1.1 : 更流畅,更快捷,更实用
  6. SQL 连接字符串的说明(转)
  7. RSS你会用了吗?答曰:不会
  8. 使用Apriori进行关联分析(一)
  9. C#制作、打包、签名、发布Activex全过程
  10. Struts2国际化