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.
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
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);
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);
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..!!!
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 !
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...');
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);
You can load HTML directly in end
method
response.end('...<p>blahblahblah</p>...')
It's the same as
response.write('...<p>blahblahblah</p>...')
response.end()
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.
How about using express module?
var app = require('express')();
app.get('/',function(request,response){
response.sendFile(__dirname+'/XXX.html');
});
app.listen('8000');
then, you can use browser to get /localhost:8000
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!_x000D_
// ES6 style_x000D_
_x000D_
const express = require('express');_x000D_
const fs = require('fs');_x000D_
const hostname = '127.0.0.1';_x000D_
const port = 3000;_x000D_
const app = express();_x000D_
_x000D_
let cache = [];// Array is OK!_x000D_
cache[0] = fs.readFileSync( __dirname + '/index.html');_x000D_
cache[1] = fs.readFileSync( __dirname + '/views/testview.html');_x000D_
_x000D_
app.get('/', (req, res) => {_x000D_
res.setHeader('Content-Type', 'text/html');_x000D_
res.send( cache[0] );_x000D_
});_x000D_
_x000D_
app.get('/test', (req, res) => {_x000D_
res.setHeader('Content-Type', 'text/html');_x000D_
res.send( cache[1] );_x000D_
});_x000D_
_x000D_
app.listen(port, () => {_x000D_
console.log(`_x000D_
Server is running at http://${hostname}:${port}/ _x000D_
Server hostname ${hostname} is listening on port ${port}!_x000D_
`);_x000D_
});
_x000D_
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 ");
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'));
});
You could also use this snippet:
var app = require("express");
app.get('/', function(req,res){
res.sendFile(__dirname+'./dir/yourfile.html')
});
app.listen(3000);
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')
}
})
}
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}/`);
})
});
It's just really simple if you use pipe. The following is the server.js code snippet.
var http = require('http');_x000D_
var fs = require('fs');_x000D_
_x000D_
function onRequest(req, res){_x000D_
_x000D_
console.log("USER MADE A REQUEST. " +req.url);_x000D_
res.writeHead(200, {'Content-Type': 'text/html'});_x000D_
var readStream = fs.createReadStream(__dirname + '/index.html','utf8'); _x000D_
_x000D_
/*include your html file and directory name instead of <<__dirname + '/index.html'>>*/_x000D_
_x000D_
readStream.pipe(res);_x000D_
_x000D_
}_x000D_
_x000D_
http.createServer(onRequest).listen(7000);_x000D_
console.log('Web Server is running...');
_x000D_
use ejs instead of jade
npm install ejs
app.js
app.engine('html', require('ejs').renderFile);
app.set('view engine', 'html');
./routes/index.js
exports.index = function(req, res){
res.render('index', { title: 'ejs' });};
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.
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.
Source: Stackoverflow.com