TypeError: myParser.MessageParser is not a constructor
TypeError: myParser.MessageParser is not a constructor
我正在尝试编写一个自定义解析器以与串行端口库一起使用。我已经按照库提供的解析器示例进行操作,但是当我尝试实例化时,出现了标题错误。
我被卡住了,找不到任何东西。我是 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();
应该可以。
我正在尝试编写一个自定义解析器以与串行端口库一起使用。我已经按照库提供的解析器示例进行操作,但是当我尝试实例化时,出现了标题错误。
我被卡住了,找不到任何东西。我是 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();
应该可以。