Search This Blog

2015-10-26

Serving a HTML file from Node JS

We can serve static files from the HTTP servers that we create using Node.js.

we are going to take advantage of two modules to do that. Those are the "connect" module and the "serve-static" module. So "connect" is an extensible HTTP framework that allows me to plug in additional functionality into my HTTP server and "serve-static" is one of the plug-ins that we are going to use to help us serve static files easily from our applications.

Step 1: Run "npm init"

Step 2 : Insert all required parameter in 'npm init' and create the start page 'index.js'.

Step 3: In package.json , add the dependencies as below and run 'npm install'

{
  "name": "demostaticfile",
  "version": "1.0.0",
  "description": "Service Static Content from web server",
  "main": "index.js",
  "scripts": {
    "test": "echo \"Error: no test specified\" && exit 1"
  },
  "author": "MRB",
  "license": "ISC",
  "dependencies" : {
    "connect"         : "*",
    "serve-static"    : "*"
   
  }
}


Step 4: Create a folder 'public' under the root and place html and image files within the public folder.

Step 5: Write below code in your index.js

var connect=require("connect");
var serveStatic=require("serve-static");

var app=connect()
  .use(serveStatic('public'))
  .use(function  (req,res) {
   res.end("Welcome to the Static Demo");
  })
  .listen(7878);

console.log("listening from port 7878");

Step 6: Open your browser and try browsing your test html file or image file

http://localhost:7878/test.html

No comments: