Dieses Blog durchsuchen

Freitag, 19. August 2016

node.js: create a little bit more complex webserver

In the last tutorial, we have created a simple webserver. Lets create a little bit more complex webserver with node.js, which can serv different filetypes and check for errors on the filesystem.

Prerequisits

node.js installed
npm installed

Create a webserver


This webserver can dispatch a hand full of images , text, javascript and css

Create a file "server.js" and paste following code
const http = require('http');
const url = require('url');
const path = require('path');
const fs = require('fs');
const mimeTypes =
{
"html":"text/html",
"jpg":"image/jpg",
"jpeg":"image/jpeg",
"png":"image/png",
"css":"text/css",
"javascript":"text/javascript"
}
http.createServer(function(req, res){
var uri = url.parse(req.url).pathname;
console.log(uri);
var fileName = path.join(process.cwd(), unescape(uri));
console.log('Loading' + uri);
var stats;
try
{
stats = fs.lstatSync(fileName);
}
catch(e)
{
res.writeHead(404,{'Content-Type':'text/plain'});
res.write('404 Not found\n');
res.end();
return;
}
if(stats.isFile())
{
var mimeType = mimeTypes[path.extname(fileName).split(".").reverse()[0]];
res.writeHead(200,{'Content-type': mimeType});
var fileStream = fs.createReadStream(fileName);
fileStream.pipe(res);
}else if(stats.isDirectory())
{
res.writeHead(302,{'location':'index.html'});
}else
{
res.writeHead(500, {'Content-type':'text/plain'});
res.write('500 internal Error\n');
res.end;
}
}).listen(1337);
view raw server hosted with ❤ by GitHub

This will create the webserver

Create a file to dispatch

Open a terminal in the projectroot and create a file "index.html" with following content
 
<html>
<head></head>
<body>
<h1>Testing</h1>
</body>
</html>
view raw index.html hosted with ❤ by GitHub



Start the webserver

Open a terminal in the projectroot and type:
$ node server.js 


Now you can surf http://localhost:1337/index.html and you should see "Testing"

Thats it

Keine Kommentare:

Kommentar veröffentlichen