1.安装node
cd /usr/local/
npm init -y
npm config set registry https://registry.npmmirror.com
npm install ffi-napi express cors
2.创建node.service
[Unit]
Description=Service
After=network.target
[Service]
Type=simple
WorkingDirectory=/usr/local/app
ExecStart=/usr/bin/node /usr/local/app/server.js
Restart=on-failure
[Install]
WantedBy=multi-user.target
3.编写server.js
const express = require('express');
const ffi = require('ffi-napi');
const cors = require('cors');
const { exec } = require('child_process');
const path = require('path');
const app = express();
const port = 3000;
app.use(cors());
app.post('/api/test/:port', (req, res) => {
const port = req.params.port;
exec(`/usr/bin/test${port}`, (error, stdout, stderr) => {
if (error) {
console.error(`exec error: ${error}`);
return res.status(500).send('Internal Server Error');
}
res.send(stdout.trim());
});
});
app.listen(port, () => {
console.log(`Node.js server listening at http://localhost:${port}`);
});
4.编写调用的app.js
function test(port) {
const url = `/api/test/${port}`;
fetch(url, {
method: 'POST',
headers: {
'Content-Type': 'application/text',
},
})
.then(response => {
if (!response.ok) {
throw new Error('Network response was not ok ' + response.statusText);
}
return response.text();
})
.then(data => {
console.log('Success:', data);
})
.catch(error => {
console.error('There was a problem with the fetch operation:', error);
});
}
5.编写shell脚本