Using node.js as a simple web server


I want to run a very simple HTTP server. Every GET request to should get index.html served to it but as a regular HTML page (i.e., same experience as when you read normal web pages).

Using the code below, I can read the content of index.html. How do I serve index.html as a regular web page?

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/plain'});

One suggestion below is complicated and requires me to write a get line for each resource (CSS, JavaScript, images) file I want to use.

How can I serve a single HTML page with some images, CSS and JavaScript?

11/19/2015 12:22:21 AM

You can use Connect and ServeStatic with Node.js for this:

  1. Install connect and serve-static with NPM

    $ npm install connect serve-static
  2. Create server.js file with this content:

    var connect = require('connect');
    var serveStatic = require('serve-static');
    connect().use(serveStatic(__dirname)).listen(8080, function(){
        console.log('Server running on 8080...');
  3. Run with Node.js

    $ node server.js

You can now go to http://localhost:8080/yourfile.html

1/13/2019 11:18:04 AM

Licensed under: CC-BY-SA with attribution
Not affiliated with: Stack Overflow