Node.js和Johnny-Five“文档未定义”错误

时间:2014-11-21 04:17:53

标签: javascript css node.js johnny-five

我正在使用带有Arduino Uno微控制器的Node.js和Johnny-Five。我的目标是,在按下连接到Arduino的按钮后,网页将显示按条形式按下的次数。

在控制台中,当我按下“未定义文档”的按钮并引用我应该更改css样式的变量时,我收到错误:

var bar1 = document.getElementById('bar1');

不确定为什么会出错。有什么想法吗?以下是我的javascript:

var five = require("johnny-five"),
  bumper, led, counter, toggleState;
  toggleState = false;

five.Board().on("ready", function() {

  bumper = new five.Button(7);
  led = new five.Led(13);
  counter = 200;

  bumper.on("hit", function() {

    led.on();
    console.log( "Button has been pressed" );
            counter += 10; //add 10 everytime the button is pressed

            console.log(counter);
            toggleState = true;
            console.log("on");

    //function increaseBarSize () {
    if(toggleState == true) {
        var bar1 = document.getElementById('bar1');
        bar1.style.width = counter;
        console.log(bar1);
    }

    }).on("release", function() {
        led.off();
        console.log("off");

    });

    });

1 个答案:

答案 0 :(得分:1)

它正在发生,因为服务器端没有DOM,你需要发送这个值并在客户端管理DOM。

试试这个:

服务器端

var express = require('express');
var app = express();
var http = require('http').Server(app);
var io = require('socket.io').listen(http);
var five = require("johnny-five"),
bumper, led, counter, toggleState;
toggleState = false;
five.Board().on("ready", function() {

    bumper = new five.Button(7);
    led = new five.Led(13);
    counter = 200;

    bumper.on("hit", function() {

        led.on();
        console.log( "Button has been pressed" );
        counter += 10; //add 10 everytime the button is pressed

        console.log(counter);
        toggleState = true;
        console.log("on");

        //function increaseBarSize () {
        if(toggleState == true) {
            io.on('connection', function(socket){
              socket.emit('counter', counter);
            });
        }

    }).on("release", function() {
        led.off();
        console.log("off");

    });
});
app.get('/', function(req, res){
    res.sendFile(__dirname + '/<client page>.html'); //change <client page> to the client document
});
http.listen(3000, function(){
    console.log('listening on *:3000');
});

客户端

 <script src="/socket.io/socket.io.js"></script>
 <script>
 var socket = io('http://localhost:3000');
 var bar1 = document.getElementById('bar1');
 socket.on('counter', function(counter){
     bar1.style.width = counter;
 });
 <script>

注意 :假设您已安装Socket.io并表达模块。