Serving static files

If we have information stored on disk that we want to serve as web content, we can use the fs (filesystem) module to load our content and pass it through the createServer callback. This is a basic conceptual starting point for serving static files. As we will learn in the following recipes there are much more efficient solutions.

Getting ready

We'll need some files to serve. Let's create a directory named content, containing the following three files:

index.html:

	<html>
	<head>
	<title>Yay Node!</title>
	<link rel=stylesheet href=styles.css type=text/css>
	<script src=script.js type=text/javascript></script>
	</head>
	<body>
	<span id=yay>Yay!</span>
	</body>
	</html>

script.js:

window.onload=function() {alert('Yay Node!');};

styles.css: ...

Get Node Cookbook now with O’Reilly online learning.

O’Reilly members experience live online training, plus books, videos, and digital content from 200+ publishers.