[英]node.js Transfer and saving files using TCP Server
我有很多设备将消息发送到写在节点中的TCP Server。 TCP服务器的主要任务是将某些消息路由到Redis,以便由另一个应用程序进行处理。
我编写了一个简单的服务器,可以很好地完成这项工作。 代码的结构基本上是这样(不是实际的代码,细节被隐藏了):
const net = require("net");
net.createServer(socket => {
socket.on("data", buffer => {
const data = buffer.toString();
if (shouldRouteMessage(data)) {
redis.publish(data);
}
});
});
大多数消息就像: {"text":"message body"}
或{"lng":32.45,"lat":12.32}
。 但是有时我需要处理跨越多个“数据”事件的消息,例如{"audio":"...encoded audio..."}
。
在这种情况下,我需要将编码的音频保存到文件中,然后发送到redis {"audio":"path/to/audio-file.mp3"}
,其中路由是接收到音频数据的文件。
一个简单的选择是存储缓冲区,直到我检测到消息的结尾,然后将所有缓冲区保存到文件中,但这意味着,除其他外,我必须在保存到磁盘之前将文件保留在内存中。
我希望使用流和管道有更好的选择。 有什么建议么? (一些代码示例,会很好)
谢谢
我终于解决了,因此我将解决方案发布在这里出于文档目的(并且很幸运,可以帮助其他人)。
实际上,解决方案非常简单:只需打开一个写入文件的流,然后在接收到数据包时将其写入即可。 像这样:
const net = require("net");
const fs = require("fs");
net.createServer(socket => {
socket.on("data", buffer => {
let file = null;
let filePath = null;
const data = buffer.toString();
if (shouldRouteMessage(data)) {
// just publish the message
redis.publish(data);
} else if (isAudioStart(data)) {
// create a write stream to a file and write the first data packet
filePath = buildFilePath(data);
file = fs.createWriteStream(filePath);
file.write(data);
} else if (isLastFragment(data)) {
// if is the last fragment, write it, close the file and publish the result
file.write(data);
file.close();
redis.publish(filePath);
file = filePath = null;
} else if (isDataFragment(data)) {
// just write (stream) it to file
file.write(data);
}
});
});
注意: shouldRouteMessage
, buildFilePath
, isDataFragment
和isLastFragment
是取决于数据类型的自定义函数。
这样,传入的数据将直接传输到文件中,而无需先将内容保存在内存中。 节点的溪流岩石!
一如既往,魔鬼在细节中。 例如,必须进行一些检查才能确保要写入文件时始终有文件。 还记得在转换为字符串时还要设置正确的编码(例如: buffer.toString('binary');
帮了我buffer.toString('binary');
)。 根据您的数据格式, shouldRouteMessage
, isAudioStart
...以及所有这些自定义函数可能或多或少复杂。
希望能帮助到你。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.