Created
March 15, 2015 05:33
-
-
Save SubhashiniSundaresan/834a81d8f19f706bd5ad to your computer and use it in GitHub Desktop.
Render HTML file in ExpressJS
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
app.listen(3000); | |
console.log("Running at Port 3000"); | |
Final words: | |
Right now we are resolving path in each router. You can optimize this little bit. Express have configuration variable which let’s you define static file path so that you don’t need to resolve path in every routes. Here is how to do so. | |
var express = require("express"); | |
var app = express(); | |
app.use(express.static(__dirname + '/View')); | |
//Store all HTML files in view folder. | |
app.use(express.static(__dirname + '/Script')); | |
//Store all JS and CSS in Scripts folder. | |
app.get('/',function(req,res){ | |
res.sendFile('index.html'); | |
//It will find and locate index.html from View or Scripts | |
}); | |
app.get('/about',function(req,res){ | |
res.sendFile('/about.html'); | |
}); | |
app.get('/sitemap',function(req,res){ | |
res.sendFile('/sitemap.html'); | |
}); | |
app.listen(3000); | |
console.log("Running at Port 3000"); | |
This code will work in similar way as above one. | |
Conclusion: | |
There are scenarios where you need to develop web server which delivers HTML files like how your apache do. However this is not the optimal use of Node.js but you can use such feature to achieve custom web server for your own application. | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment