如何修复此错误:
socket.emit('temperature',{number: data.toString().substring(69)/1000}
^
TypeError: Cannot call method 'toString' of undefined
at /home/pi/app/mano3/app.js:28:49
at fs.js:207:20
at Object.oncomplete (fs.js:107:15)
var Gpio = require('onoff').Gpio;
var sqlite3 = require('sqlite3');
var sys = require('sys');
var gpio = require("gpio");
led = new Gpio(17, 'out');
var http = require('http');
var fs = require('fs');
var count = 0;
var db = new sqlite3.Database('./db.db');
var server = http.createServer(function(req,res){
fs.readFile('./index.html', function(error, data){
res.writeHead(200,{'Content-Type':'text/html'});
res.end(data, 'utf-8');
});
}).listen(3000);
console.log('Server is running');
var io = require('socket.io').listen(server);
io.sockets.on('connection', function(socket){
console.log('User connected');
setInterval(function(){
fs.readFile('/sys/bus/w1/devices/28-00000494bf1a/w1_slave', function(error, data){
console.log(data.toString().substring(69)/1000);
socket.emit('temperature',{number: data.toString().substring(69)/1000});
});
}, 1000);
});
答案 0 :(得分:0)
data
对象没有返回值,所以我猜你在
fs.readFile('/sys/bus/w1/devices/28-00000494bf1a/w1_slave', function(error, data){
console.log(data.toString().substring(69)/1000);
socket.emit('temperature',{number: data.toString().substring(69)/1000});
});
在访问数据之前先检查错误
fs.readFile('/sys/bus/w1/devices/28-00000494bf1a/w1_slave', function(error, data){
if( error ) {
// so something with the error
return;
}
console.log(data.toString().substring(69)/1000);
socket.emit('temperature',{number: data.toString().substring(69)/1000});
});