node-serialport 是一个 Node.js 的包,用来对串口数据进行读写操作。
基本示例代码:
var SerialPort = require("serialport").SerialPort
var serialPort = new SerialPort("/dev/tty-usbserial1", {
baudrate: 57600
}, false); // this is the openImmediately flag [default is true]
serialPort.open(function (error) {
if ( error ) {
console.log('failed to open: '+error);
} else {
console.log('open');
serialPort.on('data', function(data) {
console.log('data received: ' + data);
});
serialPort.write("ls\n", function(err, results) {
console.log('err ' + err);
console.log('results ' + results);
});
}
});
罗列所有串口:
var serialPort = require("serialport");
serialPort.list(function (err, ports) {
ports.forEach(function(port) {
console.log(port.comName);
console.log(port.pnpId);
console.log(port.manufacturer);
});
});