[英]Read Serial port data using node js
I want to read data from serial port and get from data when reqested我想从串口读取数据并在需要时从数据中获取
Here is my code这是我的代码
const http = require('http');
const hostname = 'localhost';
const { SerialPort } = require('serialport')
const { ReadlineParser } = require('@serialport/parser-readline')
const { io } = require('socket.io');
let express = require('express')
const serialPort = new SerialPort({
path: 'COM4',
baudRate: 9600 ,
})
const parser = serialPort.pipe(new ReadlineParser({ delimiter: '\r\n' }))
let app = express();
var port = 8080;
const server = http.createServer(app);
server.listen(port, hostname, () => {
console.log(`Server running at http://${hostname}:${port}/`);
});
app.get('/get_data', function(req, res) {
parser.on('data', function(data) {
res.json({'weight': data});
});
});
When i am try to get data i got ERR_HTTP_HEADERS_SENT: Cannot set headers after they are sent to the client I want serial port data when requested from localhost:8080/get_data anyone can help?当我尝试获取数据时,我得到了 ERR_HTTP_HEADERS_SENT:将标头发送到客户端后无法设置标头我需要从 localhost:8080/get_data 请求时的串行端口数据任何人都可以提供帮助吗?
Your data event from parser
is probably firing more than once, which means you would be calling res.json
more than once.来自
parser
的数据事件可能不止一次触发,这意味着您将不止一次调用res.json
。 As you can see in the express api documentation , res.json
sets the content-type
header...thus you can only call it once per request.正如您在express api 文档中看到的那样,
res.json
设置content-type
header...因此每个请求只能调用一次。 Hence the error.因此错误。
What I think would normally be done in this kind of situation is to set up a queuing system.我认为在这种情况下通常会做的是建立一个排队系统。 A simple version might be done using an array, although if you were using this in a production server it might be better to use a proper message queuing system (eg rabbitMQ, kafka, AWS SQS, etc).
一个简单的版本可以使用数组来完成,但如果您在生产服务器中使用它,则使用适当的消息队列系统(例如 rabbitMQ、kafka、AWS SQS 等)可能会更好。
Here's an example of how you might use an array:下面是一个如何使用数组的示例:
const queue = [];
parser.on('data', function(data) {
// push new data onto end of queue (array)
queue.push(data);
});
app.get('/get_data', function(req, res) {
if (req.params.getFullQueue === 1) {
// empty complete contents of current queue,
// sent to client as an array of { weight: x } objects
const data = queue.splice(0, queue.length)
.map(x => ({ weight: x }));
res.json(data);
} else {
// get oldest enqueued item, send it only
res.json({ weight: queue.shift() });
}
});
The if/else
in the app.get
is meant to illustrate these two options, depending on which you wanted to use. app.get
中的if/else
旨在说明这两个选项,具体取决于您要使用的选项。 In production you'd probably want to implement pagination, or maybe even a websocket or EventSource so that data could be pushed as it became available.在生产环境中,您可能想要实现分页,或者甚至是 websocket 或 EventSource,以便在数据可用时推送数据。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.