我正在尝试编写一个与串行端口库一起使用的自定义解析器。我遵循了库提供的解析器的示例,但是当我尝试实例化时,我收到了标题错误。
我被困在这个问题上,找不到任何东西。我是 JS 初学者,所以很可能我错过了一些明显的东西。代码从命令行执行:'C:> Node speed.js'。
在 msgParser.js 中:
const Buffer = require('safe-buffer').Buffer;
const Transform = require('stream').Transform;
module.exports = class MessageParser extends Transform
{
constructor()
{
//options = options || {};
super();
this.delimiter = 0xA4;
this.msg = Buffer.alloc(0);
this.bytesNeeded = 0;
}
_transform(chunk, encoding, callback)
{
//etc
}
_flush(cb)
{
this.push(this.msg);
this.msg = Buffer.alloc(0);
cb();
}
};
在 speed.js 中:
/* jshint esversion: 6 */
/* jshint node: true */
'use strict';
const config = require('./config.json');
const serial = require('serialport');
const myParser = require('./msgParser.js');
const msgParser = new myParser.MessageParser();
const monitor = new serial.parsers.Readline({ delimiter: '\r\n' });
var port = new serial(config.serialPort, { baudRate: config.baudRate, highwatermark: 1024 });
port.pipe(msgParser).pipe(monitor);
最佳答案
您正在定义整个导出而不是导出上的属性。这会起作用。
const MessageParser = require('./msgParser.js');
const msgParser = new MessageParser();
应该可以。
关于javascript - 类型错误:myParser.MessageParser 不是构造函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49478665/