12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091 |
- var app = require('express')();
- var server = require('http').Server(app);
- var io = require('socket.io')(server);
- var fs = require('fs');
- var port = process.env.PORT;
- var sockets = [];
- var Files = {};
- app.get('/', function (req, res) {
- res.sendFile(__dirname + '/public/index.html');
- });
- io.on('connection', (socket) => {
- sockets.push(socket);
- socket.on('disconnect', (data) => {
- console.log("Socket disconnect");
- var index = sockets.indexOf(socket);
- if (index > -1) {
- sockets.splice(index, 1);
- }
- });
- addEvents(socket);
- });
- server.listen(800);
- function addEvents(socket){
- socket.on("wannafile", function(data){
- var name = data.name;
- console.log("File incoming");
- console.log(data);
- if(!name)return;
- if(!Files[name]){
- Files[name] = {
- position : 0,
- total : data.size,
- Data : ""
- }
- }
- var Name = name;
- var entry = Files[name];
- try{
- var Stat = fs.statSync('Temp/' + Name);
- if(Stat.isFile())
- {
- Files[Name]['position'] = Stat.size;
- }
- }
- catch(er){} //It's a New File
- fs.open("Temp/" + Name, "a", 0755, function(err, fd){
- if(err)
- {
- console.log(err);
- }
- else
- {
- Files[Name]['Handler'] = fd; //We store the file handler so we can write to it later
- socket.emit(name, {position: Files[name].position, total: Files[name].total});
- }
- });
- });
- socket.on("upload", function(data){
- var Name = data.name;
- Files[Name].position += data['data'].length;
- Files[Name]['Data'] += data['data'];
- if(Files[Name]['position'] == Files[Name]['total']) //If File is Fully Uploaded
- {
- fs.write(Files[Name]['Handler'], Files[Name]['Data'], null, 'Binary', function(err, Writen){
- console.log("File is finished!");
- socket.emit(Name, { position : Files[Name].position, total : Files[Name].total});
- });
- }
- else if(Files[Name]['Data'].length > 10485760){ //If the Data Buffer reaches 10MB
- console.log("Buffer is full!");
- fs.write(Files[Name]['Handler'], Files[Name]['Data'], null, 'Binary', function(err, Writen){
- Files[Name]['Data'] = ""; //Reset The Buffer
- socket.emit(Name, { position : Files[Name].position, total : Files[Name].total});
- });
- }
- else
- {
- socket.emit(Name, { position : Files[Name].position, total : Files[Name].total});
- }
- });
- }
|