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(\'...blahblahblah
...\
we can load the html document with connect frame work. I have placed my html document and the related images in the public folder of my project where the below code and node modules present.
//server.js
var http=require('http');
var connect=require('connect');
var app = connect()
.use(connect.logger('dev'))
.use(connect.static('public'))
.use(function(req, res){
res.end('hello world\n');
})
http.createServer(app).listen(3000);
I have tried the readFile() method of fs, but it fails to load the images, that's why i have used the connect framework.
https://gist.github.com/xgqfrms-GitHub/7697d5975bdffe8d474ac19ef906e906
Here is my simple demo codes for host static HTML files by using Express server!
hope it helps for you!
// simple express server for HTML pages!
// ES6 style
const express = require('express');
const fs = require('fs');
const hostname = '127.0.0.1';
const port = 3000;
const app = express();
let cache = [];// Array is OK!
cache[0] = fs.readFileSync( __dirname + '/index.html');
cache[1] = fs.readFileSync( __dirname + '/views/testview.html');
app.get('/', (req, res) => {
res.setHeader('Content-Type', 'text/html');
res.send( cache[0] );
});
app.get('/test', (req, res) => {
res.setHeader('Content-Type', 'text/html');
res.send( cache[1] );
});
app.listen(port, () => {
console.log(`
Server is running at http://${hostname}:${port}/
Server hostname ${hostname} is listening on port ${port}!
`);
});