使用 Node.js 从 txt 文件中读取坐标

Read coordinates from txt file with Node.js

我正在从 RFID 传感器接收一些坐标并将其保存在 .txt 文件中。我需要读取这些坐标并应用一些计算(矩阵微积分)。

如何实时阅读?我注意到我无法使用 FS,因为我的 .txt 文件从未完成,我的传感器每秒都在保存数据。

这些是我在文本文件中的坐标:

{"coordinates":{"x":-775,"y":-1217,"z":780},"tagId":"26459"}
{"coordinates":{"x":-152,"y":-113,"z":-1327},"tagId":"26398"}
{"coordinates":{"x":-770,"y":-1185,"z":731},"tagId":"26459"}
{"coordinates":{"x":-137,"y":-104,"z":-1337},"tagId":"26398"}

我相信只要你在处理流,你仍然可以使用 FS。

例如,您可以执行以下操作:

const textFilePath = 'path/to/txt/file';
let stream = fs.createReadStream(textFilePath);

stream.on("data", (data) => {
  let chunk = data.toString();
  // Do something here with the data chunk ...
});

以同样的方式,您可以对文件进行流式写入以确保一致的块事务。

stream.write(coordinateObject);

您需要使用 node-red-node-tail node.

此节点专门满足您的需求。

您将需要 运行 通过 JSON 节点将字符串转换为 JSON 对象的消息,以便您可以访问每一行中的字段。