JavaScript消息在nodejs中传递

任何人都可以请帮助我如何做到这一点? 每次收到消息时,我都想把消息从websocket传递到串口

var firmata = require('firmata'); var board = new firmata.Board('COM4'); var WebSocketServer = require('ws').Server; var wss = new WebSocketServer({ port: 8081 }); wss.on('connection', function connection(websocket) { websocket.on('message', function incoming(message) { board.servoWrite(5, message); //This doesn't work but how do i send? } board.on("ready", function() { board.servoWrite(5, 0); // this works but i need the message from above which I cant access. }); 

board准备就绪后,您应该添加监听器。

 board.on("ready", function() { wss.on('connection', function connection(websocket) { websocket.on('message', function incoming(message) { board.servoWrite(5, message); }); }); }); 

要么或者声明一个variables,告诉你它是否准备好了。

 var isReady = false; board.on("ready", function() { isReady = true; }); wss.on('connection', function connection(websocket) { websocket.on('message', function incoming(message) { if(isReady) board.servoWrite(5, message); }); }); 

它不是一个sytax错误..不得不补充

 board.servoConfig(5, 0, 30); 

我把它添加到这样的代码中:

 var firmata = require('firmata'); var board = new firmata.Board('COM4',function(){ }); var WebSocketServer = require('ws').Server; var wss = new WebSocketServer({ port: 8081 }); wss.on('connection', function connection(websocket) { websocket.on('message', function incoming(message) { board.servoConfig(5, 0, 30); board.servoWrite(5, message); //This doesn't work but how do i send? } board.on("ready", function() { board.servoWrite(5, 0); // this works but i need the message from above which I cant access. });