Node Server responding with dynamic HTML by parsing html file as string
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
var http = require('http'); | |
var fs = require('fs'); | |
http.createServer(function(req, res) { | |
// Specify html content type | |
res.writeHead(200, { 'Content-Type': 'text/html' }); | |
// Read contents of index.htm file synchronously, | |
// Saved as string in var html. | |
// Use 'utf8' param to specify encoding and ensure you are | |
// dealing with a string rather than a buffer. | |
var html = fs.readFileSync(__dirname + '/index2.htm', 'utf8'); | |
var message = 'Bostom Creme Donut'; | |
// Takes html string and replaces instances of | |
// '{Message}' with value of message var | |
html = html.replace('{Message}', message); | |
// Send contents of index.htm file as body of response | |
res.end(html); | |
}).listen(1337, '127.0.0.1'); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment