[英]Node.js and Johnny-Five “document is not defined” error
I am using Node.js and Johnny-Five with an Arduino Uno micro controller. 我正在将Node.js和Johnny-Five与Arduino Uno微控制器一起使用。 My goal is to, upon pressing the button hooked up to the Arduino, the webpage will display a count of the number of times it has been pressed in the form of a bar.
我的目标是,在按下连接到Arduino的按钮后,该网页将以条形形式显示其被按下的次数。
In console I get an error when I press the button that says "document is not defined" and references my variable that is supposed to change the css styling: 在控制台中,当我按下显示“未定义文档”的按钮并引用我的应该更改css样式的变量时,我得到一个错误:
var bar1 = document.getElementById('bar1');
Not sure why that is giving an error. 不知道为什么会给出错误。 Any thoughts?
有什么想法吗? Below is my javascript:
以下是我的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");
});
});
It's happening because there isn't DOM on the server side, you need to send this value and manage the DOM at the client side. 之所以发生这种情况是因为服务器端没有DOM,您需要发送此值并在客户端管理DOM。
Try this: 尝试这个:
SERVER SIDE 服务器端
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');
});
CLIENT SIDE 客户端
<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>
NOTE : assume that you already installed Socket.io and express modules. 注意 :假设您已经安装了Socket.io和express模块。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.