如何避免在服务器中构建整个HTML页面?

时间:2016-06-22 14:55:58

标签: javascript html node.js

如果你在client.on方法上查看下面的代码,我会重写整个输出文件,因为我不知道如何使用html文件显示消息。是否有类似的方式来做这个而不是重写任何东西? Res.write也很慢,而当我使用res.send它非常快。有没有其他方法可以做到这一点?我对节点js来说相当新。

//Sending UDP message to TFTP server
//dgram modeule to create UDP socket
var express= require('express'), fs= require('fs'),path = require('path'),util = require('util'),dgram= require('dgram'),client= dgram.createSocket('udp4'),bodyParser = require('body-parser'),app = express()
// parse application/x-www-form-urlencoded
app.use(bodyParser.urlencoded({ extended: false }))
// parse application/json
app.use(bodyParser.json())
app.use(express.static('public'));

//Reading in the html file for input page
app.get('/', function(req, res){
    var html = fs.readFileSync('index2.html');
    res.writeHead(200, {'Content-Type': 'text/html'});
    res.end(html);
});

//reading in html file for output page
app.get('/output', function(req, res){
    var html = fs.readFileSync('index3.html');
    res.writeHead(200, {'Content-Type': 'text/html'});
    res.end(html);
});

//Recieving UDP message 
app.post('/output', function(req, res){
//Define the host and port values of UDP
var HOST= '192.168.0.136';
var PORT= 69;
//Reading in the user's command, converting to hex
var message = new Buffer(req.body.number, 'hex');

//Sends packets to TFTP
client.send(message, 0, message.length, PORT, HOST, function (err, bytes) {
        if (err) throw err;
  });

//Recieving message back and printing it out to webpage
client.on('message', function (message) {
  res.write('<html>');
  res.write('<head>');
  res.write('<meta name="viewport" content="width=device-width">');
  res.write('<link rel="stylesheet" type="text/css" href="style.css" media="screen" />');
  res.write('</head>');
  res.write('</body>');
  res.write('<img src="logo.png" alt="rolls royce logo">');
  res.write('<ul>');
  res.write('<li><a href="/">Input</a></li>');
  res.write('<li><a class="active" href="/output">Output</a></li>');
  res.write(' </ul>');
  res.write('</br></br>')
  res.write('<div>');
  res.write(' <h4>Output is:</h4>');
  res.write(message.toString());
  res.write('</div>');
  res.write('</body>');
  res.write('</html>');
  });
});


//Setting up listening server
app.listen(3000, "192.168.0.136");
console.log('Listening at 192.168.0.136:3000');

1 个答案:

答案 0 :(得分:1)

您可以编写HTML模板,将其保存到可从服务器访问的文件系统的一部分,然后将其返回到具有正确值的HTTP客户端 feeded

您可以编写自己的模板引擎(并使用正则表达式进行正确的替换),或者您可以使用Jade

client.on('message', function(message) {
    fs.readFile('/etc/templates/message.jade', function(_, template) {
        let body = jade.compile(template)({
                       message: message.toString()
                   });

        return res.end(body);
    });
});

message.jade可能在哪里

doctype html
html
    body
        h4 Output is: #{message}