使用 node.js 和 javascript 更新 HTML 对象

Update HTML object with node.js and javascript

我是 nodejs 和 jquery 的新手,我正在尝试使用脚本更新一个 html 对象。 我正在使用 Raspberry pi 2 和超声波传感器来测量距离。我想连续测量,并用实时值同时更新 html 文档。

当我尝试 运行 我的代码时,它表现得像服务器而不是客户端。 i console.log() 在 cmd 中而不是在浏览器的控制台中打印的所有内容。当我 运行 我的代码现在我用 "sudo node surveyor.js" 来做,但是 html 文档中没有任何反应。我已将其正确链接到脚本。我也试过document.getElementsByTagName("h6").innerHTML = distance.toFixed(2),但是错误是"document is not defiend"。

有什么简单的方法可以解决这个问题吗?

到目前为止我的代码是:

var statistics = require('math-statistics');
var usonic = require('r-pi-usonic');
var fs = require("fs");
var path = require("path");
var jsdom = require("jsdom");

var htmlSource = fs.readFileSync("../index.html", "utf8");



var init = function(config) {
    usonic.init(function (error) {
        if (error) {
        console.log('error');
        } else {
            var sensor = usonic.createSensor(config.echoPin, config.triggerPin, config.timeout);
            //console.log(config);
            var distances;

            (function measure() {
                if (!distances || distances.length === config.rate) {
                    if (distances) {
                        print(distances);
                    }

                    distances = [];
                }

                setTimeout(function() {
                    distances.push(sensor());

                    measure();
                }, config.delay);
            }());
        }
    });
}; 

var print = function(distances) {
    var distance = statistics.median(distances);

    process.stdout.clearLine();
    process.stdout.cursorTo(0);

    if (distance < 0) {
        process.stdout.write('Error: Measurement timeout.\n');
    } else {
        process.stdout.write('Distance: ' + distance.toFixed(2) + ' cm');

        call_jsdom(htmlSource, function (window) {
            var $ = window.$;
            $("h6").replaceWith(distance.toFixed(2));
            console.log(documentToSource(window.document));
});

    }
};


function documentToSource(doc) {
    // The non-standard window.document.outerHTML also exists,
    // but currently does not preserve source code structure as well

    // The following two operations are non-standard
    return doc.doctype.toString()+doc.innerHTML;
}

function call_jsdom(source, callback) {
    jsdom.env(
        source,
        [ 'jquery-1.7.1.min.js' ],
        function(errors, window) {
            process.nextTick(
                function () {
                    if (errors) {
                        throw new Error("There were errors: "+errors);
                    }
                    callback(window);
                }
            );
        }
    );
}

init({
    echoPin: 15, //Echo pin
    triggerPin: 14, //Trigger pin
    timeout: 1000, //Measurement timeout in µs
    delay: 60, //Measurement delay in ms
    rate: 5 //Measurements per sample
});

Node.js 是 JavaScript 的服务器端实现。在服务器端进行所有传感器操作和计算是可以的,但是您需要某种机制来将结果提供给您的客户端。如果他们要通过网络浏览器使用您的应用程序,您必须 运行 一个 HTTP 服务器,例如 Express.js, and create a route (something like http://localhost/surveyor or just http://localhost/) that calls a method you have implemented on server-side and do something with the result. One possible way to return this resulting data to the clients is by rendering an HTML page that shows them. For that you should use a Template Engine.

任何 DOM 操作都应该在客户端完成(例如,您可以在模板中包含一个 <script> 标记 HTML 只是为了尝试了解它是如何工作的,但不推荐在生产环境中这样做)。

尝试在 google 中搜索 Node.js 个示例和教程,您会得到它:)