NodeJS新手求助:TypeError: serialport.parsers.readline is not a function错误
TypeError: serialport.parsers.readline is not a function in Node.js Hey there! I’ve helped a bunch of folks troubleshoot this exact error, and it’s almost always related to a breaking API change in the SerialPort library—not a Node.js/npm version mismatch (though that’s a totally reasonable guess!). Let’s break down how to fix this:
Why this happens
Starting with SerialPort v10.0.0, the way you import and use parsers changed completely. The old serialport.parsers.readline syntax was removed, so if you’re using a newer version of SerialPort with code written for v9 or earlier, you’ll hit this error.
Step-by-step fixes
1. Check your SerialPort version first
Run this command in your project folder to confirm which version you’re using:
npm list serialport
2. If you’re using SerialPort v10+ (recommended)
Update your code to use the new parser import syntax. Here’s the before/after:
Old code (v9 and below):
const SerialPort = require('serialport'); const readlineParser = SerialPort.parsers.readline; const parser = new readlineParser('\n'); // Attach parser to port port.pipe(parser);
New code (v10+):
// Import SerialPort and the Readline parser separately const { SerialPort } = require('serialport'); const { ReadlineParser } = require('@serialport/parser-readline'); // Initialize your port first const port = new SerialPort({ path: '/your-serial-port-path', // e.g., COM3 on Windows, /dev/ttyUSB0 on Linux baudRate: 9600 // match your device's baud rate }); // Pipe the port to the Readline parser const parser = port.pipe(new ReadlineParser({ delimiter: '\n' })); // Now you can listen for data like before parser.on('data', (data) => { console.log('Received:', data); });
3. If you want to stick with the old syntax
If you don’t want to update your code, install the latest v9.x version of SerialPort:
npm install serialport@9.x --save
This will let you keep using serialport.parsers.readline without changes.
4. Double-check your dependencies
Sometimes corrupted node modules can cause weird issues. If the above steps don’t work:
- Delete your
node_modulesfolder andpackage-lock.jsonfile - Run
npm installto reinstall all dependencies fresh
Final note
If you’re still stuck, feel free to share a snippet of your full SerialPort code—I can help tweak it further!
内容的提问来源于stack exchange,提问作者panther93

