Skip to content

Instantly share code, notes, and snippets.

@matthewoestreich
Created June 7, 2020 22:34
Show Gist options
  • Save matthewoestreich/10b9d9758f6ca51757159652d1094129 to your computer and use it in GitHub Desktop.
Save matthewoestreich/10b9d9758f6ca51757159652d1094129 to your computer and use it in GitHub Desktop.
Vanilla Node.js with Mustache
const http = require('http');
const fs = require('fs');
const mustache = require('mustache');
const hostname = '127.0.0.1';
const port = 3000;
const server = http.createServer((req, res) => {
if (req.url === '/') {
if (req.method === 'GET') {
const data = {
name: "John Doe",
age: "99"
};
const template = String(fs.readFileSync('./test.mustache', 'utf8'));
const rendered = mustache.render(template, data);
res.statusCode = 200;
res.end(rendered);
}
}
});
server.listen(port, hostname, () => {
console.log(`Server running at http://${hostname}:${port}/`);
});
{
"name": "xxxxxxxxx",
"version": "1.0.0",
"description": "",
"main": "index.js",
"dependencies": {
"mustache": "^4.0.1"
},
"author": "",
"license": "ISC"
}
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
</head>
<body>
{{#name}}
<h1>Name: {{name}}</h1>
{{/name}}
{{#age}}
<h1>Age: {{age}}</h1>
{{/age}}
</body>
</html>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment