我检查过这种问题。但我没有找到任何。如果你找到了请告诉我 我刚开始通过node.js和serialport编写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,
});
任何帮助将不胜感激。
答案 0 :(得分:2)
您的代码是正确的,除非您使用serialPort
库的require('serialport')
对象,而实际上SerialPort
需要使用undefined is not a function
,因此var SerialPort = require("serialport")
console.log(SerialPort.serialPort); // undefined
console.log(SerialPort.SerialPort); // { [Function: SerialPort, ... }
你遇到的错误。
{{1}}
有关示例用法,请参阅the documentation。
答案 1 :(得分:0)
尝试一下。它运作完美。
var SerialPort = require('serialport');
var serialPort = SerialPort.serialPort;
var sp = new SerialPort("/dev/ttyACM0", {
});