Create a node.js web server

1 min read

Summary

Simple snippet showing how web pages can be served using node.js.

Pure Node.js

var http = require("http");
var fs = require("fs");
var index = fs.readFileSync("index.html");

http
  .createServer(function (req, res) {
    res.writeHead(200, { "Content-Type": "text/html" });
    res.end(index);
  })
  .listen(8080);

Node.js with Express

npm install express --save
var express = require("express"),
  path = require("path"),
  app = express();

// Express Middleware for serving static files
app.use(express.static(path.join(__dirname, "/public")));

app.get("/", function (req, res) {
  res.redirect("index.html");
});

app.listen(8080);

Note that all static files that need to be served must be placed in the /public folder:

/Public
./js/script.js
./css/style.css
./index.html
server.js

You must be logged in to post a comment.