nodejs作为一切皆异步的始祖编程语言,其性能自然不必多说。http server也是做常用的开发工具,这里就写一段基于nodejs的http server代码。
另外,额外添加mqtt client的代码端。话不多说,上代码:
const http = require("http") const process = require('child_process') const mqtt = require('mqtt') let mqttclient = mqtt.connect('mqtt://localhost', { username: 'username', password: 'password', will: { topic: 'devicewill', payload: 'device disconnect', qos: 0, retain: false } }) mqttclient.on('connect', function () { mqttclient.subscribe('presence', function (err) { if (err) { console.log(err) } }) }) mqttclient.on('message', function (topic, message) { let obj = JSON.parse(message.toString()) if (obj.act === "/api/runcmd") { process.exec(obj.cmd, function(err, stdout, stderr) { if (err) { console.log(err, "launch cmd fail.") } else { console.log("launch cmd success.") } }) } }) function getbody (req) { return new Promise(function (resolve, reject) { let body = '' req.on("data", function(data) { body += data; }) req.on("end", function () { resolve(body) }) }) } http.createServer(async function (req, res) { if (req.url === "/api/runcmd") { let body = await getbody(req) process.exec(body, function(err, stdout, stderr) { if (err) { console.log(err) res.writeHead(200, {"Content-Type":"text/plain","Access-Control-Allow-Origin":"*"}) res.end(JSON.stringify({ "errcode": -2, "errmsg": "launch cmd fail." })) } else { res.writeHead(200, {"Content-Type":"text/plain","Access-Control-Allow-Origin":"*"}) res.end(JSON.stringify({ "errcode": 0 })) } }) } else { res.writeHead(200, {"Content-Type":"text/plain","Access-Control-Allow-Origin":"*"}) res.end(JSON.stringify({ "errcode": -99, "errmsg": "unknown api" })) } }).listen(80)
文章作者:沃航科技