56

I have a simple html page with angular js as follows:

    //Application name
    var app = angular.module("myTmoApppdl", []);

    app.controller("myCtrl", function ($scope) {
        //Sample login function
        $scope.signin = function () {
            var formData =
                    {
                        email: $scope.email,
                        password: $scope.password
                    };
        console.log("Form data is:" + JSON.stringify(formData));
    };
});

HTML file:

<html>
    <head>
        <link href="bootstrap.min.css" rel="stylesheet" type="text/css"/>
    </head>

    <body ng-app="myTmoApppdl" ng-controller="myCtrl">
        <div class="container">
            <div class="form-group">
                <form class="form" role="form" method="post" ng-submit="signin()">
                    <div class="form-group col-md-6">
                        <label class="">Email address</label>
                        <input type="email" class="form-control" ng-model="email" id="exampleInputEmail2" placeholder="Email address" required>
                    </div>
                    <div class="form-group col-md-6">
                        <label class="">Password</label>
                        <input type="password" class="form-control" id="exampleInputPassword2" ng-model="password" placeholder="Password" required>
                    </div>
                </form>
                <button type="submit" class="btn btn-primary btn-block">Sign in</button>
            </div>
        </div>
    </body>

    <script src="angular.min.js" type="text/javascript"></script>

    <!--User defined JS files-->
    <script src="app.js" type="text/javascript"></script>
    <script src="jsonParsingService.js" type="text/javascript"></script>
</html>

I am new to node js. I have installed node js server in my system but I am not sure how to run a simple html file using node js?

3
  • 1
    "Actually this will run even copy/pasted somewhere in your desktop."
    – daniel
    Commented Mar 14, 2016 at 18:33
  • 1
    You can't "run html file" with node.js. Node.js is a JavaScript environment for developing server-side Web applications. Html files are usually run by web-browsers. Commented Mar 14, 2016 at 18:35
  • Node.js does not "run" HTML files. You probably just want a server that serves static files.
    – SLaks
    Commented Mar 14, 2016 at 18:35

13 Answers 13

53

You can use built-in nodejs web server.

Add file server.js for example and put following code:

var http = require('http');
var fs = require('fs');

const PORT=8080; 

fs.readFile('./index.html', function (err, html) {

    if (err) throw err;    

    http.createServer(function(request, response) {  
        response.writeHeader(200, {"Content-Type": "text/html"});  
        response.write(html);  
        response.end();  
    }).listen(PORT);
});

And after start server from console with command node server.js. Your index.html page will be available on URL http://localhost:8080

7
  • I should put this in file called app.js?
    – kittu
    Commented Mar 14, 2016 at 18:39
  • Do I have to add it to script tag in html?
    – kittu
    Commented Mar 14, 2016 at 18:40
  • @Satyadev It's doesn't matter how you call this file. This file is responsible for server side...
    – Alexandr
    Commented Mar 14, 2016 at 18:42
  • I am getting errors like this: 2 'require' was used before it was defined. var http = require('http'); 5 Expected an identifier and instead saw 'const'. const PORT=8080; 5 Stopping. (26% scanned). const PORT=8080;
    – kittu
    Commented Mar 14, 2016 at 18:44
  • It just prints It Works!! Path Hit: /index.htm
    – kittu
    Commented Mar 14, 2016 at 18:47
34

Just install http-server globally

npm install -g http-server

where ever you need to run a html file run the command http-server For ex: your html file is in /home/project/index.html you can do /home/project/$ http-server

That will give you a link to accessyour webpages: http-server Starting up http-server, serving ./ Available on: http://127.0.0.1:8080 http://192.168.0.106:8080

5
  • 1
    This is probably the most straightforward, no? Commented Jul 15, 2018 at 17:06
  • I don't think this is a great solution. You should not install npm packages globally when it can be avoided. The whole entire Node infrastructure has moved decidedly away from throwing a -g into everything.
    – Raydot
    Commented Aug 1, 2018 at 23:09
  • I tried installing installing http-server without -g and node through an error when I tried to start the server. It seems that -g is still required when instaling this particular package. Commented Apr 4, 2019 at 20:11
  • Installing globally requires sudo so I installed without the -g in my project directory. Then, I ran index.html, which is in the project directory, as node_modules/http-server/bin/http-server.
    – tash
    Commented Dec 14, 2020 at 16:54
  • Actually, I ran into a question--how to daemonize it? In the above method, it would run on a shell. So unless I use screen like app or able to keep my shell open forever, the server would get cut-off at some point.
    – tash
    Commented Dec 15, 2020 at 5:12
21

I too faced such scenario where I had to run a web app in nodejs with index.html being the entry point. Here is what I did:

  • run node init in root of app (this will create a package.json file)
  • install express in root of app : npm install --save express (save will update package.json with express dependency)
  • create a public folder in root of your app and put your entry point file (index.html) and all its dependent files (this is just for simplification, in large application this might not be a good approach).
  • Create a server.js file in root of app where in we will use express module of node which will serve the public folder from its current directory.
  • server.js

    var express = require('express');
    var app = express();
    app.use(express.static(__dirname + '/public')); //__dir and not _dir
    var port = 8000; // you can use any port
    app.listen(port);
    console.log('server on' + port);
    
  • do node server : it should output "server on 8000"

  • start http://localhost:8000/ : your index.html will be called

File Structure would be something similar

2
  • I found a better solution than mine : stackoverflow.com/questions/6084360/… check out Tony's answer and upvote there. Commented Jan 9, 2017 at 16:27
  • I actually liked your answer more. It's quick and easy and uses native Node functionality without installing excessive packages. Commented May 5, 2018 at 20:19
13

Move your HTML file in a folder "www". Create a file "server.js" with code :

var express = require('express');
var app = express();

app.use(express.static(__dirname + '/www'));

app.listen('3000');
console.log('working on 3000');

After creation of file, run the command "node server.js"

4
  • 1
    This is the simplest configuration I see and worked like charm :)
    – Irfan Raza
    Commented Jun 8, 2019 at 15:04
  • cannot find module 'express' Commented Dec 7, 2021 at 16:14
  • 1
    @MindRoasterMir That's because express is a package/framework. You'd have to add it to your package.json first -- npm install express etc etc. More at that other question. It is much easier to use than http, however, especially if you want to serve, say, the CSS and other associated includes for your html file.
    – ruffin
    Commented Jul 1, 2022 at 14:21
  • npm install --save express is a prerequisite
    – abhi
    Commented Apr 4, 2023 at 15:48
7

The simplest command by far:

npx http-server

This requires an existing index.html at the dir at where this command is being executed.

This was already mentioned by Vijaya Simha, but I thought using npx is way cleaner and shorter. I am running a webserver with this approach since months.

Docs: https://www.npmjs.com/package/http-server

2
  • it runs but not on my desired port, can you please how to assign on custom port? thank you Commented Dec 18, 2019 at 4:39
  • @AljohnYamaro npx http-server -p 8080
    – codepleb
    Commented Dec 18, 2019 at 10:44
5

http access and get the html files served on 8080:

>npm install -g http-server

>http-server

if you have public (./public/index.html) folder it will be the root of your server if not will be the one that you run the server. you could send the folder as paramenter ex:

http-server [path] [options]

expected Result:

*> Starting up http-server, serving ./public Available on:

http://LOCALIP:8080

http://127.0.0.1:8080

Hit CTRL-C to stop the server

http-server stopped.*

Now, you can run: http://localhost:8080

will open the index.html on the ./public folder

references: https://www.npmjs.com/package/http-server

2

This is a simple html file "demo.htm" stored in the same folder as the node.js file.

<!DOCTYPE html>
<html>
  <body>
    <h1>Heading</h1>
    <p>Paragraph.</p>
  </body>
</html>

Below is the node.js file to call this html file.

var http = require('http');
var fs = require('fs');

var server = http.createServer(function(req, resp){
  // Print the name of the file for which request is made.
  console.log("Request for demo file received.");
  fs.readFile("Documents/nodejs/demo.html",function(error, data){
    if (error) {
      resp.writeHead(404);
      resp.write('Contents you are looking for-not found');
      resp.end();
    }  else {
      resp.writeHead(200, {
        'Content-Type': 'text/html'
      });
      resp.write(data.toString());
      resp.end();
    }
  });
});

server.listen(8081, '127.0.0.1');

console.log('Server running at http://127.0.0.1:8081/');

Intiate the above nodejs file in command prompt and the message "Server running at http://127.0.0.1:8081/" is displayed.Now in your browser type "http://127.0.0.1:8081/demo.html".

1
  • Your code is pretty unreadable with that spacing and indentation. Please correct these to make it easier for future readers. Commented Feb 27, 2018 at 17:29
1

Either you use a framework or you write your own server with nodejs.

A simple fileserver may look like this:

import * as http from 'http';
import * as url from 'url';
import * as fs from 'fs';
import * as path from 'path';

var mimeTypes = {
     "html": "text/html",
     "jpeg": "image/jpeg",
     "jpg": "image/jpeg",
     "png": "image/png",
     "js": "text/javascript",
     "css": "text/css"};

http.createServer((request, response)=>{
    var pathname = url.parse(request.url).pathname;
    var filename : string;
    if(pathname === "/"){
        filename = "index.html";
    }
    else
        filename = path.join(process.cwd(), pathname);

    try{
        fs.accessSync(filename, fs.F_OK);
        var fileStream = fs.createReadStream(filename);
        var mimeType = mimeTypes[path.extname(filename).split(".")[1]];
        response.writeHead(200, {'Content-Type':mimeType});
        fileStream.pipe(response);
    }
    catch(e) {
            console.log('File not exists: ' + filename);
            response.writeHead(404, {'Content-Type': 'text/plain'});
            response.write('404 Not Found\n');
            response.end();
            return;
    }
    return;
    }
}).listen(5000);
4
  • @SLaks Nice I did not know this package. PS. the posted code was only my debug version. The release version consists only of one server.js file.
    – Matthias
    Commented Mar 14, 2016 at 18:38
  • @Matthias I followed the other answer posted by @JILeXanDR but it prints only It Works!! Path Hit: /index.htm after running. Could you please tell what I am doing wrong?
    – kittu
    Commented Mar 14, 2016 at 18:50
  • 1
    @Satyadev Yes, this is because of the line response.end('It Works!! Path Hit: ' + request.url); Maybe you should read a short tutorial about nodejs
    – Matthias
    Commented Mar 14, 2016 at 18:53
  • You can replace the import statements by the require statements. Ans save this code. In server.js file too.
    – Matthias
    Commented Mar 14, 2016 at 18:57
1

In order to deploy a html pages via Node JS project, For example to deploy an Angular build file where the all the requests needed to be redirected to index.html in that case we can use the wild card route of node js to serve the Angular project but we need to make sure that there are no naming conflicts of Angular route and Node js API route.

app.js

//Angular App Hosting Production Build
app.use(express.static(__dirname + '/dist/ShoppingCart'));

// For all GET requests, send back index.html (PathLocationStrategy) (Refresh Error)
app.get('*', (req,res) => {
  res.sendFile(path.join(__dirname, '/dist/ShoppingCart/index.html'));
});

1
app.get('/home', (req, res) => {
    res.sendFile(__dirname + '/home.html');
});
2
  • 1
    This answer is in the "low quality answers queue" and may be voted for deletion. I suggest you try to expand the content detail to avoid that happening.
    – moken
    Commented Aug 7, 2023 at 4:19
  • Although this code might answer the question, I recommend that you also provide an explanation what your code does and how it solves the problem of the question. Answers with an explanation are usually more helpful and of better quality, and are more likely to attract upvotes. Commented Aug 9, 2023 at 9:07
1

If you want to run the html file in your browser then you can do following steps:

step 1 --> You need to create server and listen on some port

step 1 eg --->

app.listen(PORT, () => {
  console.log(`Server running at http://localhost:${PORT}/`);
});

step 2 --> You can make the route like / or /profile for your html webpage

step 2.1 --> Now in this route you can use sendFile function in node js

step 2.1 eg --->

app.get('/', (req, res) => {
  res.sendFile(path.join(__dirname, 'index.html'));
});
0
const http = require('http');
const fs = require('fs');
var mimeTypes = {
    "html": "text/html",
    "jpeg": "image/jpeg",
    "jpg": "image/jpeg",
    "png": "image/png",
    "js": "text/javascript",
    "css": "text/css"
};

var server = http.createServer((req, res) => {
    if (req.url === '/') {
        res.writeHeader(200, { "Content-Type": "text/html" });
        fs.createReadStream('./public/index.html').pipe(res)
    }
    var filesDepences = req.url.match(/\.js|.css/);
    if (filesDepences) {
         var extetion = mimeTypes[filesDepences[0].toString().split('.')[1]];
        res.writeHead(200, { 'Content-Type': extetion });
        fs.createReadStream(__dirname + "/public" + req.url).pipe(res)
    }
})

server.listen(8080);
2
  • 1
    Your answer could be improved by adding more information on what the code does and how it helps the OP.
    – Tyler2P
    Commented Apr 3, 2022 at 7:37
  • thanks I thought about what he needed, that's why I didn't make the code longer Commented Apr 4, 2022 at 11:42
0

Let us take an example,

My HTML file (test.html)

<html>
<body>
<h1> Hello World </h1>
</body>
</html>

Just c++ has libraries we have modules in Node.js, These modules can be very helpful for doing different processes using Node.js If you dont have any idea about modules in Node.js i will suggest you to read following article : https://www.w3schools.com/nodejs/nodejs_modules.asp

Here we are going to use two modules [http] for creating server and [fs] for opening our html file assuming which is located in same folder of our app.js file, now let us see app.js code:

var http = require('http');                                   // Import the http module
var fs   = require('fs');                                     // Import the fs (filesystem) module

// Create an HTTP server
http.createServer(function(req, res) {
  // Read the contents of the file 'test.html'
  
  fs.readFile('test.html', function(err, data) {
    if (err) 
    {
      // If there's an error reading the file, send a 500 error response
      res.writeHead(500, {'Content-Type': 'text/plain'});     // Set the response header
      res.write('Error: Unable to load file');                // Write the error message
      return res.end();
    }
    
    // If the file is read successfully, send the file content as the response
    
    res.writeHead(200, {'Content-Type': 'text/html'});        // Set the response header
    res.write(data);                                          // Write the file content
    return res.end();                                         // End the response
  });
}).listen(8080);                                              // The server listens on port 8080

Thank you !! I hope this should resolve your issue :)

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.