Last active
January 19, 2020 19:00
-
-
Save debonx/c0dcd918d4b5f77c92146fb9e962ae22 to your computer and use it in GitHub Desktop.
Node: Create an HTTP server rendering a simple HTML app.
This file contains hidden or 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
<!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> |
This file contains hidden or 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
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(); | |
} | |
}) | |
} | |
} |
This file contains hidden or 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
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