Loading basic HTML in Node.js


Question

I'm trying to find out how to load and render a basic HTML file so I don't have to write code like:

response.write('...<p>blahblahblah</p>...');
1
196
8/3/2019 8:40:42 AM

Accepted Answer

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!

226
8/13/2014 12:48:09 AM

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


Licensed under: CC-BY-SA with attribution
Not affiliated with: Stack Overflow
Icon