var http = require('http');
var util = require('util');
var url = require('url');
var path = require("path");
var iconv = require("iconv-lite");
var fs = require("fs");
var Buffer = require("Buffer");
var marked = require('marked');
var num = 8080;
fs.readFile(process.cwd()+"/server.log",function(err,data){
    if(err){
        server(num)
    }else{
        server(num);
    }
});
function server(data){
	var server = http.createServer(function (req, res) {
		console.log('Request received: ');
		util.log(util.inspect(req)); // this line helps you inspect the request so you can see whether the data is in the url (GET) or the req body (POST)
		util.log('Request recieved: \nmethod: ' + req.method + '\nurl: ' + req.url); // this line logs just the method and url
		var arg = url.parse(req.url, true).query;
		res.writeHead(200, { 'Content-Type': 'text/plain;charset=utf-8' });
		var des_file = arg.fileUrl+arg.name;
		
		fs.readFile( arg.url, function (err, data) {
			
			fs.writeFile(des_file, data, function (err) {
			 if( err ){
				 res.end('callback(\'{\"msg\": \"0\"}\')');
			 }else{
				 res.end('callback(\'{\"msg\": \"1\"}\')');
			 }
		   });
	   });
	
	}).listen(data);
	server.on('listening', function() {
		fs.writeFile(process.cwd()+"/server.log", data, function (err) {});
	});
	server.on('error', function(err) {
	   data++;
	   server.listen(data);
	});
}
/*http.createServer(function (req, res) {
	console.log( req);
   file_stream = fs.createReadStream( file_path );      
   file_stream.on( 'data' , function( chunk ){
	 response.write( chunk );
   } ); 
   file_stream.on( 'end' , function(  ){
	 response.end( "" );
	 console.log( "文件读取完毕" );
   } );
   file_stream.on('error', function(err){
	 response.end( "文件读取失败！" );
   });

}).listen(10326);*/