Questions And Answers

More Tutorials

NodeJS Deliver HTML or any other sort of file

Deliver HTML at specified path

Here's how to create an Express server and serve index.html by default (empty path /), and page1.html for /page1 path.

Folder structure

project root
| server.js
 | index.html
 | page1.html


var express = require('express');
var path = require('path');
var app = express();
// deliver index.html if no file is requested
app.get("/", function (request, response) {
 response.sendFile(path.join(__dirname, 'views/index.html'));
// deliver page1.html if page1 is requested
app.get('/page1', function(request, response) {
 response.sendFile(path.join(__dirname, 'views', 'page1.html', function(error) {
 if (error) {
 // do something in case of error
 response.end(JSON.stringify({error:"page not found"}));

Note that sendFile() just streams a static file as response, offering no opportunity to modify it. If you are serving an HTML file and want to include dynamic data with it, then you will need to use a template engine such as Pug, Mustache, or EJS.


In this page (written and validated by ) you learned about NodeJS Deliver HTML or any other sort of file . What's Next? If you are interested in completing NodeJS tutorial, your next topic will be learning about: NodeJS TCP Sockets.

Incorrect info or code snippet? We take very seriously the accuracy of the information provided on our website. We also make sure to test all snippets and examples provided for each section. If you find any incorrect information, please send us an email about the issue:

Share On:

Mockstacks was launched to help beginners learn programming languages; the site is optimized with no Ads as, Ads might slow down the performance. We also don't track any personal information; we also don't collect any kind of data unless the user provided us a corrected information. Almost all examples have been tested. Tutorials, references, and examples are constantly reviewed to avoid errors, but we cannot warrant full correctness of all content. By using, you agree to have read and accepted our terms of use, cookies and privacy policy.