I want to run a very simple HTTP server. Every GET request to example.com
should get index.html
served to it but as a regular HTML page (i.e., same
Node.js sample app Node Chat has the functionality you want.
In it's README.textfile
3. Step is what you are looking for.
step1
- create a server that responds with hello world on port 8002
step2
- create an index.html and serve it
step3
- introduce util.js
- change the logic so that any static file is served
- show 404 in case no file is found
step4
- add jquery-1.4.2.js
- add client.js
- change index.html to prompt user for nickname
Here is the server.js
Here is the util.js
var http = require('http');
var fs = require('fs');
var index = fs.readFileSync('index.html');
http.createServer(function (req, res) {
res.writeHead(200, {'Content-Type': 'html'});
res.end(index);
}).listen(9615);
//Just Change The CONTENT TYPE to 'html'
You can just type those in your shell
npx serve
Repo: https://github.com/zeit/serve.
The simpler version which I've came across is as following. For education purposes, it is best, because it does not use any abstract libraries.
var http = require('http'),
url = require('url'),
path = require('path'),
fs = require('fs');
var mimeTypes = {
"html": "text/html",
"mp3":"audio/mpeg",
"mp4":"video/mp4",
"jpeg": "image/jpeg",
"jpg": "image/jpeg",
"png": "image/png",
"js": "text/javascript",
"css": "text/css"};
http.createServer(function(req, res) {
var uri = url.parse(req.url).pathname;
var filename = path.join(process.cwd(), uri);
fs.exists(filename, function(exists) {
if(!exists) {
console.log("not exists: " + filename);
res.writeHead(200, {'Content-Type': 'text/plain'});
res.write('404 Not Found\n');
res.end();
return;
}
var mimeType = mimeTypes[path.extname(filename).split(".")[1]];
res.writeHead(200, {'Content-Type':mimeType});
var fileStream = fs.createReadStream(filename);
fileStream.pipe(res);
}); //end path.exists
}).listen(1337);
Now go to browser and open following:
http://127.0.0.1/image.jpg
Here image.jpg
should be in same directory as this file.
Hope this helps someone :)
Basically copying the accepted answer, but avoiding creating a js file.
$ node
> var connect = require('connect'); connect().use(static('.')).listen(8000);
Found it very convinient.
As of latest version of Express, serve-static has become a separate middleware. Use this to serve:
require('http').createServer(require('serve-static')('.')).listen(3000)
Install serve-static
first.
This is basically an updated version of the accepted answer for connect version 3:
var connect = require('connect');
var serveStatic = require('serve-static');
var app = connect();
app.use(serveStatic(__dirname, {'index': ['index.html']}));
app.listen(3000);
I also added a default option so that index.html is served as a default.