Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
302 views
in Technique[技术] by (71.8m points)

reactjs - Can you control a unit outside your home with JavaScript? For example, shut down a Raspberry Pi 3 with the button "Shut down" on a web page

A few years ago I made a UI using 7-inch touchscreen connected to Raspberry Pi 3.

I had a digital button "shut down" and it worked perfectly to send a message to the Raspberry with Java (see the code below).

try {
    Runtime.getRuntime().exec("sudo shutdown -h now");
} catch (IOException e) {
    e.printStackTrace();
}

Now I want to shut down a Raspberry Pi 3 with a "Shut down" button on a web page using JavaScript. So I assume I need to give privileges to the web server and after that send this message sudo shutdown -h now to the Raspberry. Any suggestions?

question from:https://stackoverflow.com/questions/65906800/can-you-control-a-unit-outside-your-home-with-javascript-for-example-shut-down

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

You need to use Node.js if you want to use server-side JavaScript.
Something like this:

var express = require('express')
var app = express()
const { exec } = require("child_process");

// when navigating to your http://<yourdomain>/shutdown
app.get('/shutdown', function (req, res) {
  exec("sudo shutdown -h now", (error, stdout, stderr) => {
    if (error) {
        console.log(`error: ${error.message}`);
        return;
    }
    if (stderr) {
        console.log(`stderr: ${stderr}`);
        return;
    }
    console.log(`stdout: ${stdout}`);
  });
})


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...