Created
September 2, 2015 17:02
-
-
Save gobwas/97202dc45ca05a4d58fc to your computer and use it in GitHub Desktop.
File receiver
This file contains 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 stat = fs.statSync("./index.html"); | |
var server = http.createServer(function(req, res) { | |
switch(req.url) { | |
case "/": { | |
res.writeHead(200, { | |
'content-type': 'text/html', | |
'content-length': stat.size | |
}); | |
var reading = fs.createReadStream("./index.html"); | |
reading.pipe(res); | |
return; | |
} | |
case "/form": { | |
var writing = fs.createWriteStream("./file"); | |
var shouldRead = parseInt(req.headers['content-length']); | |
req.on('readable', function() { | |
var chunk; | |
var buffer = []; | |
while (shouldRead > 0 && null !== (chunk = req.read(shouldRead))) { | |
shouldRead-= chunk.length; | |
buffer.push(chunk); | |
console.log('is buffer', Buffer.isBuffer(chunk)); | |
} | |
var result = Buffer.concat(buffer); | |
writing.write(result, function() { | |
writing.end(); | |
res.writeHead(200); | |
res.end(); | |
}); | |
}); | |
break; | |
} | |
default: { | |
console.log('405', req.url); | |
res.writeHead(405); | |
res.end(); | |
} | |
} | |
}); | |
server.listen(8081, '127.0.0.1'); | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment