Created
March 2, 2015 18:59
-
-
Save morokhovets/b8f315b3582a0bf5288a to your computer and use it in GitHub Desktop.
node.js server for uploading/downloading kurento recordings (RecorderEndpoint HTTP PUT method)
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'), | |
fs = require('fs'), | |
path = require('path'), | |
static = require('node-static'); | |
var PORT = 8897, | |
RECORDINGS_DIR = './directory-to-store-recordings'; // CHANGE THIS | |
var fileServer = new static.Server(RECORDINGS_DIR); | |
http.createServer(function(req, res) { | |
switch (req.method) { | |
case 'PUT': | |
doPut(req, res); | |
break; | |
case 'GET': | |
doGet(req, res); | |
break; | |
default: | |
error_404(res); | |
} | |
}).listen(PORT, function() { | |
console.log('Listening for requests on port ' + PORT); | |
}); | |
function getFilename(req) { | |
return "filename.webm"; // CHANGE THIS: convert request params to filename | |
} | |
function doPut(req, res) { | |
var fname = getFilename(req); | |
if (fname) { | |
// assuming all chunks are received in order we can just append them | |
var writeStream = fs.createWriteStream(path.join(RECORDINGS_DIR, fname), { flags: 'a+' }); | |
req.on('data', function(data) { | |
console.log('Writing data to file: ' + data.length + ' bytes'); | |
writeStream.write(data); | |
}); | |
req.on('end', function() { | |
console.log('End of file\n'); | |
writeStream.end(); | |
res.writeHead(200); | |
res.end(); | |
}); | |
} else { | |
console.log("Bad PUT request"); | |
error404(res); | |
} | |
} | |
function doGet(req, res) { | |
var fname = getFilename(req); | |
if (fname) { | |
req.addListener('end', function () { | |
fileServer.serveFile(fname, 200, {}, req, res).on('error', function(err) { | |
console.log("Error serving file: " + err); | |
}); | |
}).resume(); | |
} else { | |
console.log("Bad GET request"); | |
error404(res); | |
} | |
} | |
function error404(res) { | |
res.writeHead(404); | |
res.end(); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment