Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Loading basic HTML in Node.js

Tags:

html

node.js

People also ask

How do you load html in node JS?

var http = require('http'), fs = require('fs'); fs. readFile('./index. html', function (err, html) { if (err) { throw err; } http. createServer(function(request, response) { response.

CAN node js work with html?

Conclusion: With simple File IO operations we can read HTML file in Node. js and by using simple modules, we can send a HTML response back to client.


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

I know this is an old question, but as no one has mentioned it I thought it was worth adding:

If you literally want to serve static content (say an 'about' page, image, css, etc) you can use one of the static content serving modules, for example node-static. (There's others that may be better/worse - try search.npmjs.org.) With a little bit of pre-processing you can then filter dynamic pages from static and send them to the right request handler.


This would probably be some what better since you will be streaming the file(s) rather than loading it all into memory like fs.readFile.

var http = require('http');
var fs = require('fs');
var path = require('path');
var ext = /[\w\d_-]+\.[\w\d]+$/;

http.createServer(function(req, res){
    if (req.url === '/') {
        res.writeHead(200, {'Content-Type': 'text/html'});
        fs.createReadStream('index.html').pipe(res);
    } else if (ext.test(req.url)) {
        fs.exists(path.join(__dirname, req.url), function (exists) {
            if (exists) {
                res.writeHead(200, {'Content-Type': 'text/html'});
                fs.createReadStream('index.html').pipe(res);
            } else {
                res.writeHead(404, {'Content-Type': 'text/html'});
                fs.createReadStream('404.html').pipe(res);
        });
    } else {
        //  add a RESTful service
    }
}).listen(8000);

This is an update to Muhammed Neswine's answer

In Express 4.x, sendfile has been deprecated and sendFile function has to be used. The difference is sendfile takes relative path and sendFile takes absolute path. So, __dirname is used to avoid hardcoding the path.

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

app.get('/', function (req, res) {
    res.sendFile(path.join(__dirname + '/folder_name/filename.html'));
});

It's more flexible and simple way to use pipe method.

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

http.createServer(function(request, response) {
  response.writeHead(200, {'Content-Type': 'text/html'});

  var file = fs.createReadStream('index.html');
  file.pipe(response);

}).listen(8080);

console.log('listening on port 8080...');