網頁的部分,使用 Express 網頁框架。使用 9000 PORT
建立 Node.js 專案,防火牆開放網頁預計使用的 9000 PORT
npm init npm install express --save #防火牆 firewall-cmd --state firewall-cmd --list-all --zone=public firewall-cmd --permanent --zone=public --add-port=9000/tcp firewall-cmd --reload
Node.js 程式內容
let express = require('express');
let app = express();
let router = express.Router();
let exec = require('child_process').exec;
let port = 9000;
//app.use(express.static(__dirname + '/public'));
//app.use('/img', express.static(__dirname + '/public/img'));
let header = '<!DOCTYPE html><html><head><title>test</title>'
+ '<meta http-equiv="Content-Type" content="text/html; charset=utf-8">'
+ '<meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=1, user-scalable=no">'
+ '</head><body><pre>';
let footer = "</pre></body></html>";
router.get('/', function (req, res, next) {
//預設頁面
console.log('index');
res.sendfile('index.html', {root: __dirname + "/public"});
});
router.get('/ls', function (req, res, next) {
//執行 ls -al 指令
exec('ls -al', function (err, stdout, stderr) {
console.log('ls');
res.send(header + stdout + footer);
});
});
app.use('/', router);
app.listen(port);
參考:
express nodejs execute ubuntu shell terminal command, ls, cat
Express.js 4.0 的路由(Router)功能用法教學 - G. T. Wang
node.js - simplest way to have Express serve a default page? - Stack Overflow
在 Express 中提供靜態檔案
沒有留言:
張貼留言