// Create server.js file:
const http = require("http");
const fs = require("fs"); // this is filesystem which allows to read and save external files
const server = http.createServer((req, res) => {
// set header content type
res.setHeader("Content-Type", "text/html");
// send html file
fs.readFile("./views/index.html", (err, data) => {
if (err) {
console.log(err);
} else {
res.end(data);
}
});
});
server.listen(3000, "localhost", () => {
console.log("listening for requests on port 3000");
});
// In directory with server.js create folder "views" and inside create file "index.html":
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Full success</title>
</head>
<body>
<h1>Ladies and Gentlemans</h1>
<h2>We're in!</h2>
</body>
</html>
// Now, open directory with server.js in terminal and run:
node server.js
// You can see the results in browser at http://localhost:3000
// NOTE: If you want to handle different adresses/pages/routes like /about, /contact or /blog search in google/grepper for "node server with routes"
const http = require('http');
const hostname = '127.0.0.1';
const port = 3000;
const server = http.createServer((req, res) => {
res.statusCode = 200;
res.setHeader('Content-Type', 'text/plain');
res.end('Hello World');
});
server.listen(port, hostname, () => {
console.log(`Server running at http://${hostname}:${port}/`);
});
// Now, run your web server using node app.js. Visit http://localhost:3000 and you
will see a message saying "Hello World".