我无法将我的node.js console.log打印到我的html文档中

问题描述 投票:0回答:1

我目前正在开发一个项目,尝试将串行打印从微控制器发送到网站。我已经制作了一个可以工作并打印所需值的 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”,但这也没有解决问题。

javascript html node.js browser arduino
1个回答
0
投票

您遇到的问题是(出于充分的*原因)浏览器限制对用户系统的直接访问。假设您的目标是在网页中显示串口数据,有一些“简单”的解决方案。

解决方案1

您的节点服务器接收并存储串行端口消息,并在服务时将这些消息嵌入到 html 中。这样您每次刷新页面时都可以看到最新版本的串行消息

    从 index.html 中删除
  • <script>
     标签
  • 设置一个占位符,例如
  • ##SERIALMESSAGES##
    
    
  • 通过追加消息将所有收到的消息存储在字符串中
  • 当提供index.html时,用消息替换占位符
<!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

更复杂,但在我看来更合适的方法是使用

websockets

使用这种方法,您将需要 js 文件,一个用于节点 (server.js) 作为后端运行,第二个在浏览器中运行 (client.js)。 Server.js 将侦听串行端口并在请求时提供 index.html(就像现在一样)。 index.html 将使用 client.js,它连接并监听 websocket。每当 websocket 收到一条消息时,它就可以将其附加到您的

<p>

 insideHtml 以“实时”显示新消息。

现在 backend.js 还需要启动一个 client.js 可以连接的 websocket 服务器,然后串行端口上接收到的所有消息都可以转发到 client.js(以及浏览器)可以接收和显示的 websocket。

如果您有任何疑问,请务必告诉我。我很乐意提供任何进一步的帮助!

© www.soinside.com 2019 - 2024. All rights reserved.