A simple web server with node.js

I do a lot of things in node.js lately. For anyone who heard node.js for the first time I quote the description from the official website:

Node.js is a platform built on Chrome’s JavaScript runtime for easily building fast, scalable network applications. Node.js uses an event-driven, non-blocking I/O model that makes it lightweight and efficient, perfect for data-intensive real-time applications that run across distributed devices.

I needed a simple web server, which serves – as the name said – simple web pages. By simple I mean static html content, in other words, pages without a template engine and without writing html within the node JavaScript.

I found Express which does the job very well. To install Express use the command


npm install express

The following sample creates a web server that is listening on port 80. Furthermore it serves all pages within the configured htmlDir directory.

var express = require("express");
var app = express();
var port = 80;
var htmlDir = "./client/"
 
app.configure(function () {
    app.use(
        "/", 
        express.static(htmlDir)
    );
});

app.listen(port);

console.log("express is working in dir " + htmlDir + " and listening on port " + port);

Advertisements
This entry was posted in Node.js and tagged , , . Bookmark the permalink.

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s