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
...\
You could also use this snippet:
var app = require("express");
app.get('/', function(req,res){
res.sendFile(__dirname+'./dir/yourfile.html')
});
app.listen(3000);
Best way i learnt is using express with html files as express gives lots of advantage. Also you can extend it to a Heroku platform if you want..Just saying :)
var express = require("express");
var app = express();
var path = require("path");
app.get('/',function(req,res){
res.sendFile(path.join(__dirname+'/index.html'));
});
app.listen(3000);
console.log("Running at Port 3000");
Clean and best..!!!
var http = require('http');
var fs = require('fs');
http.createServer(function(request, response) {
response.writeHeader(200, {"Content-Type": "text/html"});
var readSream = fs.createReadStream('index.html','utf8')
readSream.pipe(response);
}).listen(3000);
console.log("server is running on port number ");
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.
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...');
I think this would be a better option as it shows the URL running the server:
var http = require('http'),
fs = require('fs');
const hostname = '<your_machine_IP>';
const port = 3000;
const html=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, hostname, () => {
console.log(`Server running at http://${hostname}:${port}/`);
})
});