我目前正在开发一个项目,尝试将串行打印从微控制器发送到网站。我已经制作了一个可以工作并打印所需值的 Node.js 服务器,但是当我尝试将其发送到 html 文档时,我收到错误代码:“Uncaught ReferenceError:require 未定义”。
这是我的代码:
html:
<!DOCTYPE html>
<html>
<body>
<h1>Node.js to html code</h1>
<p>Message:</p>
<p id="message"></p>
<script src="app.js"></script>
</body>
</html>
js:
var http = require('http');
var fs = require('fs');
var index = fs.readFileSync('index.html');
var SerialPort = require('serialport');
const parsers = SerialPort.parsers;
const parser = new parsers.Readline({
delimiter: '\r\n',
});
var port = new SerialPort('COM6', {
baudRate: 9600,
dataBits: 8,
parity: 'none',
stopBits: 1,
flowControl: false,
});
port.pipe(parser);
var app = http.createServer(function (req, res) {
res.writeHead(200, { 'Content-Type': 'text/html' });
res.end(index);
});
var io = require('socket.io')(app);
io.on('connection', function (socket) {
console.log('Node is listening to port');
});
parser.on('data', function (data) {
console.log('Received data from port: ' + data);
io.emit('data', data);
socket.emit('message',data);
});
我尝试导入这个函数,因为它在 chrome 中默认没有定义。我也尝试将我的json包设置为“type”:“module”,但这也没有解决问题。
您遇到的问题是(出于充分的*原因)浏览器限制对用户系统的直接访问。假设您的目标是在网页中显示串口数据,有一些“简单”的解决方案。
您的节点服务器接收并存储串行端口消息,并在服务时将这些消息嵌入到 html 中。这样您每次刷新页面时都可以看到最新版本的串行消息
<script>
标签
##SERIALMESSAGES##
<!DOCTYPE html>
<html>
<body>
<h1>Node.js to html code</h1>
<p>Message:</p>
<p id="message">
##SERIALMESSAGES##
</p>
</body>
</html>
var serialMessages = ""
var app = http.createServer(function (req, res) {
res.writeHead(200, { 'Content-Type': 'text/html' });
// put the messages into index.html before serving it to the client
const indexWithMessages = index.replace("##SERIALMESSAGES##", serialMessages)
res.end(indexWithMessages);
});
parser.on('data', function (data) {
console.log('Received data from port: ' + data);
// append the received data
serialMessages += data + "\n"
io.emit('data', data);
socket.emit('message',data);
});
解决方案2<p>
insideHtml 以“实时”显示新消息。现在 backend.js 还需要启动一个 client.js 可以连接的 websocket 服务器,然后串行端口上接收到的所有消息都可以转发到 client.js(以及浏览器)可以接收和显示的 websocket。
如果您有任何疑问,请务必告诉我。我很乐意提供任何进一步的帮助!