Created
January 19, 2011 16:57
-
-
Save dstnbrkr/786445 to your computer and use it in GitHub Desktop.
Simple server that writes raw HTTP post data to a file.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
var http = require("http"); | |
var fs = require("fs"); | |
var path = require("path"); | |
http.createServer(function(request, response) { | |
unique_filename(function(filename) { | |
upload_file(filename, request, response); | |
}); | |
}).listen(8000); | |
function upload_file(filename, request, response) { | |
var fileStream = fs.createWriteStream(filename); | |
request.on('data', function(chunk) { | |
fileStream.write(chunk); | |
}); | |
request.on('end', function() { | |
fileStream.end(); | |
upload_complete(response); | |
}); | |
fileStream.on('error', function() { | |
console.log('error while writing to file'); | |
}); | |
} | |
function unique_filename(callback) { | |
var filename = ".csv"; | |
for (var i = 0; i < 10; i++) { | |
var c = Math.floor(Math.random() * 26 + 97); | |
filename = String.fromCharCode(c) + filename; | |
}; | |
path.exists(filename, function(exists) { | |
if (exists) { | |
unique_filename(callback); | |
} else { | |
console.log('Writing ' + filename); | |
callback(filename); | |
} | |
}); | |
} | |
function upload_complete(response) { | |
response.writeHead(201, {'Content-Type': 'text/plain'}); | |
response.end(); | |
} | |
console.log("> Running at http://127.0.0.1:8000/"); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment