[javascript] How to run html file using node js

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?

This question is related to javascript angularjs node.js

The answer is


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".


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


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


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"


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


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


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


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);

Examples related to javascript

need to add a class to an element How to make a variable accessible outside a function? Hide Signs that Meteor.js was Used How to create a showdown.js markdown extension Please help me convert this script to a simple image slider Highlight Anchor Links when user manually scrolls? Summing radio input values How to execute an action before close metro app WinJS javascript, for loop defines a dynamic variable name Getting all files in directory with ajax

Examples related to angularjs

AngularJs directive not updating another directive's scope ERROR in Cannot find module 'node-sass' CORS: credentials mode is 'include' CORS error :Request header field Authorization is not allowed by Access-Control-Allow-Headers in preflight response WebSocket connection failed: Error during WebSocket handshake: Unexpected response code: 400 Print Html template in Angular 2 (ng-print in Angular 2) $http.get(...).success is not a function Angular 1.6.0: "Possibly unhandled rejection" error Find object by its property in array of objects with AngularJS way Error: Cannot invoke an expression whose type lacks a call signature

Examples related to node.js

Hide Signs that Meteor.js was Used Querying date field in MongoDB with Mongoose SyntaxError: Cannot use import statement outside a module Server Discovery And Monitoring engine is deprecated How to fix ReferenceError: primordials is not defined in node UnhandledPromiseRejectionWarning: This error originated either by throwing inside of an async function without a catch block dyld: Library not loaded: /usr/local/opt/icu4c/lib/libicui18n.62.dylib error running php after installing node with brew on Mac internal/modules/cjs/loader.js:582 throw err DeprecationWarning: Buffer() is deprecated due to security and usability issues when I move my script to another server Please run `npm cache clean`