Blog

Example of Setting Up a Simple Node.js Web Page
Posted on July 10, 2015 in Node.js by Matt Jennings

Example Node.js Code in an app.js File

// get the http module
var http = require("http");

// fs module allows us to read and write content for responses
var fs = require("fs");

// creating a server using http module
var server = http.createServer(function (request, response) {
    // See what URL the clients are requesting
    console.log("client request URL: ", request.url);
    // this is how we do routing
    if(request.url == "/") {
        fs.readFile("./index.html", "utf8", function (errors, contents) {
            response.writeHead(200, {"Content-Type" : "text/html"});
            response.write(contents);
            response.end();
        });
    }

    else if(request.url === "/css/styles.css") {
        fs.readFile("./css/styles.css", "utf8", function(errors, contents) {
            response.writeHead(200, {"Content-Type": "text/css"});
            response.write(contents);
            response.end();
        });
    }

    else if(request.url === "/dojo.html") {
        fs.readFile("./dojo.html", "utf8", function(errors, contents) {
            response.writeHead(200, {"Content-Type": "text/html"});
            response.write(contents);
            response.end();
        });
    }
    // request didn't match anything
    else {
        response.writeHead(404);
        response.end("File not found!!!");
    }
});

// Tell your service which port to run on
server.listen(8000);
// print to terminal window
console.log("Running in localhost at port 8000");

Example index.html File

<html>
<head>
   
    <title>Test</title>
    <link rel="stylesheet" type="text/css" href="css/styles.css"/>
    
</head>
<body>
    
    <h1>Test</h1>
    
</body>    

</html>

styles.css File

body {
    font-family: "Helvetica Neue", Helvetica, Arial, sans-serif;
    background: red;
}

Leave a Reply