Loading basic HTML in Node.js Loading basic HTML in Node.js node.js node.js

Loading basic HTML in Node.js


I just found one way using the fs library. I'm not certain if it's the cleanest though.

var http = require('http'),    fs = require('fs');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(8000);});

The basic concept is just raw file reading and dumping the contents. Still open to cleaner options, though!


use app.get to get the html file. its simple!!

const express = require('express');const app = new express();app.get('/', function(request, response){    response.sendFile('absolutePathToYour/htmlPage.html');});

its as simple as that.For this use express module.Install express: npm install express -g


You can echo files manually using the fs object, but I'd recommend using the ExpressJS framework to make your life much easier.

...But if you insist on doing it the hard way:

var http = require('http');var fs = require('fs');http.createServer(function(req, res){    fs.readFile('test.html',function (err, data){        res.writeHead(200, {'Content-Type': 'text/html','Content-Length':data.length});        res.write(data);        res.end();    });}).listen(8000);