gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-12-03 06:40:46 41 4
gpt4 key购买 nike

如果您查看下面 client.on 方法上的代码,我会 res.write 整个输出文件,因为我不知道如何让消息与 html 文件一起显示。有没有类似的方法而不是 res.writing 任何东西? Res.write 也非常慢,而当我使用 res.send 时,它非常快。我还有其他方法可以做到这一点吗?我对 Node 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');

最佳答案

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

您可以编写自己的模板引擎(并使用正则表达式进行正确的替换),或者您可以使用 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}

关于javascript - 如何避免在服务器中构建整个 HTML 页面?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37971681/

41 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com