📦 serialport
import { SerialPort } from 'serialport'
// or
const { SerialPort } = require('serialport')
This package provides everything you need to start talking over your serialport. It provides a high level Stream Interface, auto detecting bindings, and a set of parser streams.
tip
Most of the api is covered in the Stream Interface docs.
Historically this was the only package involved and it contained everything. Since version 7 the internals have been split into their own modules and can be required separately, allowing a user to only install what they need.
This allows for smaller installs and alternative interfaces, bindings and parsers.
SerialPort​
The SerialPort
class uses the @serialport/bindings-cpp
binding with the Stream Interface class.
import { SerialPort } from 'serialport'
const serialport = new SerialPort({ path: '/dev/example', baudRate: 9600 })
serialport.write('ROBOT POWER ON')
list​
SerialPort.list()
Calls the bindings-cpp list()
function directly.
binding​
SerialPort.binding
The detected platform binding.
port​
const port = new SerialPort({ path: '/dev/robot', baudRate: 9600 })
port.port // instance of platform specific bindings
The PortBinding object opened for the port.
SerialPortMock​
The SerialPortMock
class includes the @serialport/binding-mock
binding with the Stream Interface class.
import { SerialPortMock } from 'serialport'
const path = '/dev/example'
SerialPortMock.binding.createPort(path)
const serialport = new SerialPortMock({ path, baudRate: 9600 })
serialport.write('ROBOT POWER ON')
list​
SerialPortMock.list() // Promise<PortInfo[]>
Calls the mock binding list function directly which returns all created ports.
binding​
SerialPortMock.binding
The MockBinding
class being used by the port.
port​
The port property only exists on an open port. You can't emit data when it's closed.
SerialPortMock.binding.createPort('/dev/robot')
const port = new SerialPortMock({ path: '/dev/robot', baudRate: 9600 })
port.on('open', () => {
port.port.emitData('data')
})
The MockPortBinding object opened for the port.
Parsers​
This package exports the following parsers;
- ByteLengthParser
- CCTalkParser
- DelimiterParser
- InterByteTimeoutParser
- PacketLengthParser
- ReadlineParser
- ReadyParser
- RegexParser
- SlipEncoder and SlipDecoder
- SpacePacketParser
// for example
import { SerialPort, SpacePacketParser } from 'serialport'
These Parsers
are all Transform streams that process incoming data. To use the parsers, you must create them and then pipe the Serialport to the parser. Be careful to only write to the SerialPort object and not the parser.
const { SerialPort, ReadlineParser } = require('serialport')
const port = new SerialPort({ path, baudRate })
const parser = new ReadlineParser()
port.pipe(parser)
parser.on('data', console.log)
port.write('ROBOT PLEASE RESPOND\n')
// ROBOT ONLINE
// Creating the parser and piping can be shortened to
const parser = port.pipe(new ReadlineParser())