app.js 2.5 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091
  1. var app = require('express')();
  2. var server = require('http').Server(app);
  3. var io = require('socket.io')(server);
  4. var fs = require('fs');
  5. var port = process.env.PORT;
  6. var sockets = [];
  7. var Files = {};
  8. app.get('/', function (req, res) {
  9. res.sendFile(__dirname + '/public/index.html');
  10. });
  11. io.on('connection', (socket) => {
  12. sockets.push(socket);
  13. socket.on('disconnect', (data) => {
  14. console.log("Socket disconnect");
  15. var index = sockets.indexOf(socket);
  16. if (index > -1) {
  17. sockets.splice(index, 1);
  18. }
  19. });
  20. addEvents(socket);
  21. });
  22. server.listen(800);
  23. function addEvents(socket){
  24. socket.on("wannafile", function(data){
  25. var name = data.name;
  26. console.log("File incoming");
  27. console.log(data);
  28. if(!name)return;
  29. if(!Files[name]){
  30. Files[name] = {
  31. position : 0,
  32. total : data.size,
  33. Data : ""
  34. }
  35. }
  36. var Name = name;
  37. var entry = Files[name];
  38. try{
  39. var Stat = fs.statSync('Temp/' + Name);
  40. if(Stat.isFile())
  41. {
  42. Files[Name]['position'] = Stat.size;
  43. }
  44. }
  45. catch(er){} //It's a New File
  46. fs.open("Temp/" + Name, "a", 0755, function(err, fd){
  47. if(err)
  48. {
  49. console.log(err);
  50. }
  51. else
  52. {
  53. Files[Name]['Handler'] = fd; //We store the file handler so we can write to it later
  54. socket.emit(name, {position: Files[name].position, total: Files[name].total});
  55. }
  56. });
  57. });
  58. socket.on("upload", function(data){
  59. var Name = data.name;
  60. Files[Name].position += data['data'].length;
  61. Files[Name]['Data'] += data['data'];
  62. if(Files[Name]['position'] == Files[Name]['total']) //If File is Fully Uploaded
  63. {
  64. fs.write(Files[Name]['Handler'], Files[Name]['Data'], null, 'Binary', function(err, Writen){
  65. console.log("File is finished!");
  66. socket.emit(Name, { position : Files[Name].position, total : Files[Name].total});
  67. });
  68. }
  69. else if(Files[Name]['Data'].length > 10485760){ //If the Data Buffer reaches 10MB
  70. console.log("Buffer is full!");
  71. fs.write(Files[Name]['Handler'], Files[Name]['Data'], null, 'Binary', function(err, Writen){
  72. Files[Name]['Data'] = ""; //Reset The Buffer
  73. socket.emit(Name, { position : Files[Name].position, total : Files[Name].total});
  74. });
  75. }
  76. else
  77. {
  78. socket.emit(Name, { position : Files[Name].position, total : Files[Name].total});
  79. }
  80. });
  81. }