javascript - Javascript irc bot node.js从文本文件错误中连接字符串
问题描述
我正在使用 node.js 和 IRC 库 ( https://github.com/martynsmith/node-irc ) 创建一个 irc 机器人。当我尝试连接文本文件中的字符串时,irc 机器人会关闭并引发错误。我怀疑有一些看不见的换行符会把事情搞砸,但我不知道如何测试它或在这种情况下摆脱它。
代码说明: 当用户在irc频道中输入消息时,调用myFunction。myFunction 读取名为 test.txt 的文本文件,并将行作为元素保存在名为 myArray 的数组中。然后,我尝试使用 bot.say 命令让机器人打印出该数组的一个元素。config.channels[0] 是输入消息的通道,也是机器人应该响应的通道。
机器人可以毫无问题地在不同的行上打印出 myArray[0] 和 myArray[1],但之后它不能连接任何东西。
错误信息: C:\Program Files\nodejs\node_modules\irc\lib\irc.js:849 throw err; ^ 错误 [ERR_UNHANDLED_ERROR]:未处理的错误。([object Object]) 在 Client.emit (events.js:171:17) 在客户端。(C:\Program Files\nodejs\node_modules\irc\lib\irc.js:643:26) 在 Client.emit (events.js:182:13) 在迭代器 (C:\Program Files\nodejs\node_modules\irc \lib\irc.js:846:26) at Array.forEach () at Socket.handleData (C:\Program Files\nodejs\node_modules\irc\lib\irc.js:841:15) at Socket.emit (events .js:182:13) 在 addChunk (_stream_readable.js:283:12) 在 Socket.Readable.push (_stream_readable.js:219:10) 的 readableAddChunk (_stream_readable.js:260:13)
test.txt在不同的行中包含字母 abcd。
var config = {
channels: ["#channelname"],
server: "se.quakenet.org",
botName: "testbot"
};
// Get the lib
var irc = require("irc");
// Create the bot name
var bot = new irc.Client(config.server, config.botName, {
channels: config.channels
});
// Listen for any message
bot.addListener("message", function(from, to, text, message) {
myFunction(); //call myFunction when someone types something in the channel
});
function myFunction() {
var myArray = readTextFile('test.txt');
bot.say(config.channels[0],myArray[0]); //Print out the first element in myArray (works, this prints out 'a')
bot.say(config.channels[0],myArray[1]); //Print out the second element in myArray(works, this prints out 'b')
bot.say(config.channels[0],'test' + myArray[0]); //Works, prints out 'testa'
bot.say(config.channels[0],myArray[0] + 'test'); //concatenate a string afterwards (prints out 'a' and then throws an error and makes the bot disconnect from server)
bot.say(config.channels[0],myArray[0] + myArray[1]); //prints out 'a' and then throws an error and makes the bot disconnect from server
}
//function to read a text file:
function readTextFile(file) {
var fs = require("fs");
var textFile = fs.readFileSync("./" + file, {"encoding": "utf-8"});
textFileArray = textFile.split('\n');
return textFileArray;
}
解决方案
问题是文本文件中出现了一些不好的不可见字符(尽管仍然不知道是什么字符)。在另一篇文章中找到了答案,我使用 mystring.replace(/\W/g, '') 从 myArray 中的所有元素中删除了所有非字母数字字符。
推荐阅读
- css - CSS Grid 自动调整列自动换行
- react-native - React Native - 获取 API 错误:[SyntaxError: JSON Parse error: Unexpected identifier "object"]
- c++ - c++向量没有显示我插入的任何值
- python - Python2 和 Python3 DPKT 似乎返回不同的输出格式
- apache-spark - pyspark - 在 Spark 会话中获得一致的随机值
- python - python列表中的请求问题
- javascript - 为 TSLint (NestJs) 和 ESLint (VueJs) 设置 VS Code linting
- python - DateField Django 上的数学运算
- numpy - 使用 Tensorflow 或 numpy 计算矢量化运行 bin 索引
- java - 我将一个 txt 文件读入 Java,我想让它被编码为边,其中每个边都是一对节点(DFS)