martes, 7 de enero de 2014

Start with nodejs server

var http = require('http');
var mime = require('mime');
var url = require('url');
var fs = require('fs');
var _base = './';

http.createServer(function(req, res){
 pathname = _base + req.url;
 console.log('path name: ' + pathname);
 fs.stat(pathname, function(err, stats){
  if(err){
   res.writeHead(404);
   res.write('Bad request 404 \n');
   res.end();
  }else if(stats.isFile()){
   var type = mime.lookup(pathname);
   console.log('mime-type: ' + type);
   res.setHeader('Content-Type', type);
   res.statusCode = 200;
   var file = fs.createReadStream(pathname);
   file.on('open', function(data){
    file.pipe(res);
   });
   file.on('error', function(err){
    console.log('error open the file: ' + err);
   })
  }else{
   res.writeHead(403);
   res.write('Directory access is forbidden');
   res.end();
  }
 });
}).listen(1024);
console.log('server running on 1024');

No hay comentarios:

Publicar un comentario