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>...');
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!
sys = require('util') is not needed since nothing is printed to the console.fs.readFile could be placed inside the call to http.createServer, allowing the error to be handled. Use Stephen's answer with if (err) { console.log('something bad'); return res.end('Oops! Something bad happened.');} The return statement is the simple thing that new users might overlook.use app.get to get the html file. it's simple!
const express = require('express');
const app = 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 -g express
express.var express = require('express'); var app = express(); npm install express --save instead of -gYou 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);
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...');
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'));
});
path.join - should be path.join(__dirname, 'folder_name', 'filename.html') I think?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..!!!
It's just really simple if you use pipe. The following is the server.js code snippet.
var http = require('http');
var fs = require('fs');
function onRequest(req, res){
console.log("USER MADE A REQUEST. " +req.url);
res.writeHead(200, {'Content-Type': 'text/html'});
var readStream = fs.createReadStream(__dirname + '/index.html','utf8');
/*include your html file and directory name instead of <<__dirname + '/index.html'>>*/
readStream.pipe(res);
}
http.createServer(onRequest).listen(7000);
console.log('Web Server is running...');
../. If were to do nothing but change __dirname + "/index.html' to something like __dirname + requestedPageFromHeader, I believe the resulting code would have this vulnerability. Directory pathing characters like ~ will be fine as long as you include the __dirname + - if the user can determine the start of the path will need to check for these as well.The easy way to do is, put all your files including index.html or something with all resources such as CSS, JS etc. in a folder public or you can name it whatever you want and now you can use express js and just tell app to use the _dirname as :
In your server.js using express add these
var express = require('express');
var app = express();
app.use(express.static(__dirname + '/public'));
and if you want to have seprate directory add new dir under public directory and use that path "/public/YourDirName"
SO what we are doing here exactly? we are creating express instance named app and we are giving the adress if the public directory to access all the resources. Hope this helps !
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 ");
response.writeHeader(), but rather, response.writeHead().response.writeHeader() and response.writeHead() both are valid.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}/`);
})
});
I know this is an old question - here is a simple file server utility if you'd prefer to not use connect or express; but rather the http module.
var fileServer = require('./fileServer');
var http = require('http');
http.createServer(function(req, res) {
var file = __dirname + req.url;
if(req.url === '/') {
// serve index.html on root
file = __dirname + 'index.html'
}
// serve all other files echoed by index.html e.g. style.css
// callback is optional
fileServer(file, req, res, callback);
})
module.exports = function(file, req, res, callback) {
var fs = require('fs')
, ext = require('path').extname(file)
, type = ''
, fileExtensions = {
'html':'text/html',
'css':'text/css',
'js':'text/javascript',
'json':'application/json',
'png':'image/png',
'jpg':'image/jpg',
'wav':'audio/wav'
}
console.log('req '+req.url)
for(var i in fileExtensions) {
if(ext === i) {
type = fileExtensions[i]
break
}
}
fs.exists(file, function(exists) {
if(exists) {
res.writeHead(200, { 'Content-Type': type })
fs.createReadStream(file).pipe(res)
console.log('served '+req.url)
if(callback !== undefined) callback()
} else {
console.log(file,'file dne')
}
})
}
This is a pretty old question...but if your use case here is to simply send a particular HTML page to the browser on an ad hoc basis, I would use something simple like this:
var http = require('http')
, fs = require('fs');
var server = http.createServer(function(req, res){
var stream = fs.createReadStream('test.html');
stream.pipe(res);
});
server.listen(7000);
You can use Express to load and render basic HTML files with Node. This takes about 10 minutes to get going. It's tied to the http.createServer() so your still in the land of Node and can remove it with ease.
// app.js
const path = require('path');
const express = require('express');
const app = express();
app.use(express.static(path.join(__dirname, 'public')));
app.use('/', express.static('index.html'));
app.use('/test', express.static('test.html'));
module.exports = app;
// server.js
const http = require('http');
const PORT = process.env.PORT || 3000;
const appServer = require('./app');
const httpServer = http.createServer(appServer);
httpServer.listen(PORT);
console.log(`Listening on port ${PORT}...`);
Adding another option - based on the excepted answer.
For Typescript:
import { Injectable } from '@nestjs/common';
import { parse } from 'node-html-parser';
import * as fs from 'fs';
import * as path from 'path'
@Injectable()
export class HtmlParserService {
getDocument(id: string): string {
const htmlRAW = fs.readFileSync(
path.join(__dirname, "../assets/files/some_file.html"),
"utf8"
);
const parsedHtml = parse(htmlRAW);
const className = '.'+id;
//Debug
//console.log(parsedHtml.querySelectorAll(className));
return parsedHtml.querySelectorAll(className).toString();
}
}
(*) Example above is using with nestjs and node-html-parser.
try this one:
var http = require('http');
var fs = require('fs');
var PORT = 8080;
http.createServer((req, res) => {
fs.readFile('./' + req.url, (err, data) => {
if (!err) {
var dotoffset = req.url.lastIndexOf('.');
var mimetype = dotoffset == -1 ? 'text/plaint' : {
'.html': 'text/html',
'.css': 'text/css',
'.js': 'text/javascript',
'.jpg': 'image/jpeg',
'.png': 'image/png',
'.ico': 'image/x-icon',
'.gif': 'image/gif'
}[ req.url.substr(dotoffset) ];
res.setHeader('Content-Type', mimetype);
res.end(data);
console.log(req.url, mimetype);
} else {
console.log('File not fount: ' + req.url);
res.writeHead(404, "Not Found");
res.end();
}
});
}).listen(PORT);
With this, you can include js, css source-codes when linking them and you can load icons, imgs, gifs. And if you want, you can add more if you need.
var http = require('http');
var fs = require('fs'); //required to readfile
http.createServer(function(req, response){
fs.readFile('index.html',function (err, data){
response.writeHead(200);
response.write(data);
response.end();
});
}).listen(8000);
// #just use express lol
index.html is the name of your html file
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.