Skip to content

Instantly share code, notes, and snippets.

@dstnbrkr
Created January 19, 2011 16:57
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save dstnbrkr/786445 to your computer and use it in GitHub Desktop.
Save dstnbrkr/786445 to your computer and use it in GitHub Desktop.
Simple server that writes raw HTTP post data to a file.
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