node.js - 从串口node.js创建新对象时出错

标签 node.js serial-port

我已经检查过此类问题。但我没有找到。如果你找到了。请告诉我。 我刚刚开始通过node.js 和串口编写javascript。有人可以解释一下为什么会出现这个错误吗?

/Applications/MAMP/htdocs/homeautomation/server.js:42
var sp = new serialPort(portName, {
         ^
TypeError: undefined is not a function
    at Object.<anonymous> (/Applications/MAMP/htdocs/homeautomation/server.js:42:10)
    at Module._compile (module.js:456:26)
    at Object.Module._extensions..js (module.js:474:10)
    at Module.load (module.js:356:32)
    at Function.Module._load (module.js:312:12)
    at Function.Module.runMain (module.js:497:10)
    at startup (node.js:119:16)
    at node.js:901:3

这是我的起始代码

/*
 * dependencies
 */
var express = require('express'),
    server = require('http').createServer(app),
    io = require('socket.io').listen(server),
    serialPort = require('serialport').serialPort;

server.listen(3000);
console.log('listen on port 3000')

/*
 * Express
 */

var app = express();

// serve static files from index
app.configure(function(){
    app.use(express.static(__dirname + '/'));
});


// respon to web GET request on index.html
app.get('/', function (req, res){
    res.sendfile(__dirname + '/index.html');
});


/*
 * Serial Port Setup
 */

var portName = '/dev/tty.usb.serial-A501JUTF';
//var portName = '/dev/tty.usbmodem1421';
var readData = ''; //Array to hold the values read from the port

var sp = new serialPort(portName, {
    baudRate : 9600,
    dataBits : 8,
    parity : 'none',
    stopBits: 1,
    flowControl : false,
}); 

任何帮助将不胜感激。

最佳答案

您的代码是正确的,只是您使用了 require('serialport') 库的 serialPort 对象,而它实际上是 SerialPort > 您需要使用它,因此您遇到的 undefined is not a function 错误。

var SerialPort = require("serialport")
console.log(SerialPort.serialPort); // undefined
console.log(SerialPort.SerialPort); // { [Function: SerialPort, ... }

参见the documentation示例用法。

关于node.js - 从串口node.js创建新对象时出错,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20100342/

相关文章:

java - 通过serial.read()确认从Ardulink的sendCustomMessage()收到的消息

javascript - 如何保持 Javascript 数组排序,而不对其进行排序

node.js - Rest API - 如何以正确的方式提供数据

python - 从python控制rs232 windows终端程序

c - 如何使用 C 在 Linux 中从串口读取数据?

c# - C#如何调用串口收到的数据

Node.js Fetch 说证书过期

node.js - 使用 PM2 将 Node 作为服务运行 - 连接被拒绝

node.js - buster.js 测试无法加载我的 js 文件

node.js - Nodejs 使用串口向 Arduino 发送数据