2013-12-15 62 views
0

方法「的toString」如何解決這個錯誤:類型錯誤:無法調用未定義

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

什麼樣的文件是'/ sys/bus/w1/devices/28-00000494bf1a/w1_slave'?它看起來像一個文件夾,而不是一個特定的文件... – Rikard

+1

if(error){console.log(error); } – damphat

+0

如果你有'(err,res)'回調,你應該總是檢查'err'。如果你現在不知道該怎麼做,只需使用'if(err)throw err'並確定它何時發生。 – vkurchatkin

回答

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}); 
}); 
+0

首先處理成功案例,'if(!error && data){//處理成功案例}其他{console.log(錯誤); }' – vmx

相關問題