Skip to content

Instantly share code, notes, and snippets.

@debonx
Last active January 19, 2020 19:00
Show Gist options
  • Save debonx/c0dcd918d4b5f77c92146fb9e962ae22 to your computer and use it in GitHub Desktop.
Save debonx/c0dcd918d4b5f77c92146fb9e962ae22 to your computer and use it in GitHub Desktop.
Node: Create an HTTP server rendering a simple HTML app.
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<meta http-equiv="X-UA-Compatible" content="ie=edge">
<title>My Node Server</title>
</head>
<body>
<h1>This is my own Node web server</h1>
<h2>Fucking good uh?</h2>
</body>
</html>
const fs = require('fs');
// Listen each request and send the right response (err or data)
module.exports = {
requestListener: (req, res) => {
fs.readFile('./myNodeWebsite.html', 'utf-8', (err, data) => {
if (err){
res.writeHead(200, {'Content-Type': 'text/html'});
res.write(`${err}`);
res.end();
} else {
res.writeHead(200, {'Content-Type': 'text/html'});
res.write(data);
res.end();
}
})
}
}
const http = require('http');
// Define callback
let {requestListener} = require('./node-http-callback.js');
// Define port
const PORT = process.env.PORT || 4001;
// Create HTTP server
const server = http.createServer(requestListener);
server.listen(PORT);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment