templates/node-app/server.js
2026-11-28 15:28:05 +02:00

57 lines
2.2 KiB
JavaScript

'use strict';
// A small Node.js web app with no dependencies: a home page, a JSON API route
// and a health check for Docker. Add your framework of choice when you need one.
const http = require('http');
const PORT = Number(process.env.PORT || 3000);
const SITE_NAME = process.env.SITE_NAME || 'My app';
function send(res, status, type, body) {
res.writeHead(status, {
'Content-Type': type,
'Content-Length': Buffer.byteLength(body),
'X-Content-Type-Options': 'nosniff',
});
res.end(body);
}
function escapeHtml(s) {
return String(s).replace(/[&<>"']/g, (c) => ({ '&': '&amp;', '<': '&lt;', '>': '&gt;', '"': '&quot;', "'": '&#39;' }[c]));
}
function handler(req, res) {
const url = new URL(req.url, 'http://localhost');
if (req.method !== 'GET' && req.method !== 'HEAD') {
return send(res, 405, 'application/json', JSON.stringify({ error: 'method_not_allowed' }));
}
if (url.pathname === '/health') {
return send(res, 200, 'application/json', JSON.stringify({ status: 'ok' }));
}
if (url.pathname === '/api/time') {
return send(res, 200, 'application/json', JSON.stringify({ now: new Date().toISOString() }));
}
if (url.pathname === '/') {
const name = escapeHtml(SITE_NAME);
return send(res, 200, 'text/html; charset=utf-8',
'<!doctype html><html lang="en"><head><meta charset="utf-8">' +
'<meta name="viewport" content="width=device-width, initial-scale=1">' +
'<title>' + name + '</title></head><body style="font-family:system-ui,sans-serif;max-width:40rem;margin:3rem auto;padding:0 1rem">' +
'<h1>' + name + '</h1><p>The Node.js app is running. Edit <code>server.js</code> to build on it.</p>' +
'<p>Try <a href="/api/time">/api/time</a>.</p></body></html>');
}
return send(res, 404, 'application/json', JSON.stringify({ error: 'not_found' }));
}
function start(port = PORT) {
const server = http.createServer(handler);
server.listen(port, () => console.log('listening on port ' + server.address().port));
// Docker sends SIGTERM on stop: finish open requests, then exit.
process.once('SIGTERM', () => server.close(() => process.exit(0)));
return server;
}
if (require.main === module) {
start();
}
module.exports = { handler, start };