arnaucube
arnaucube/raspberryGPIOhtmlserverPublic Self-hosted repository
raspberryGPIOhtmlserver/node_modules/ws/examples/fileapi/server.js
node_modules/ws/examples/fileapi/server.jsRaw
  1var WebSocketServer = require('../../').Server
  2  , express = require('express')
  3  , fs = require('fs')
  4  , http = require('http')
  5  , util = require('util')
  6  , path = require('path')
  7  , app = express.createServer()
  8  , events = require('events')
  9  , ansi = require('ansi')
 10  , cursor = ansi(process.stdout);
 11
 12function BandwidthSampler(ws, interval) {
 13  interval = interval || 2000;
 14  var previousByteCount = 0;
 15  var self = this;
 16  var intervalId = setInterval(function() {
 17    var byteCount = ws.bytesReceived;
 18    var bytesPerSec = (byteCount - previousByteCount) / (interval / 1000);
 19    previousByteCount = byteCount;
 20    self.emit('sample', bytesPerSec);
 21  }, interval);
 22  ws.on('close', function() {
 23    clearInterval(intervalId);
 24  });
 25}
 26util.inherits(BandwidthSampler, events.EventEmitter);
 27
 28function makePathForFile(filePath, prefix, cb) {
 29  if (typeof cb !== 'function') throw new Error('callback is required');
 30  filePath = path.dirname(path.normalize(filePath)).replace(/^(\/|\\)+/, '');
 31  var pieces = filePath.split(/(\\|\/)/);
 32  var incrementalPath = prefix;
 33  function step(error) {
 34    if (error) return cb(error);
 35    if (pieces.length == 0) return cb(null, incrementalPath);
 36    incrementalPath += '/' + pieces.shift();
 37    fs.exists(incrementalPath, function(exists) {
 38      if (!exists) fs.mkdir(incrementalPath, step);
 39      else process.nextTick(step);
 40    });
 41  }
 42  step();
 43}
 44
 45cursor.eraseData(2).goto(1, 1);
 46app.use(express.static(__dirname + '/public'));
 47
 48var clientId = 0;
 49var wss = new WebSocketServer({server: app});
 50wss.on('connection', function(ws) {
 51  var thisId = ++clientId;
 52  cursor.goto(1, 4 + thisId).eraseLine();
 53  console.log('Client #%d connected', thisId);
 54
 55  var sampler = new BandwidthSampler(ws);
 56  sampler.on('sample', function(bps) {
 57    cursor.goto(1, 4 + thisId).eraseLine();
 58    console.log('WebSocket #%d incoming bandwidth: %d MB/s', thisId, Math.round(bps / (1024*1024)));
 59  });
 60
 61  var filesReceived = 0;
 62  var currentFile = null;
 63  ws.on('message', function(data, flags) {
 64    if (!flags.binary) {
 65      currentFile = JSON.parse(data);
 66      // note: a real-world app would want to sanity check the data
 67    }
 68    else {
 69      if (currentFile == null) return;
 70      makePathForFile(currentFile.path, __dirname + '/uploaded', function(error, path) {
 71        if (error) {
 72          console.log(error);
 73          ws.send(JSON.stringify({event: 'error', path: currentFile.path, message: error.message}));
 74          return;
 75        }
 76        fs.writeFile(path + '/' + currentFile.name, data, function(error) {
 77          ++filesReceived;
 78          // console.log('received %d bytes long file, %s', data.length, currentFile.path);
 79          ws.send(JSON.stringify({event: 'complete', path: currentFile.path}));
 80          currentFile = null;
 81        });
 82      });
 83    }
 84  });
 85
 86  ws.on('close', function() {
 87    cursor.goto(1, 4 + thisId).eraseLine();
 88    console.log('Client #%d disconnected. %d files received.', thisId, filesReceived);
 89  });
 90
 91  ws.on('error', function(e) {
 92    cursor.goto(1, 4 + thisId).eraseLine();
 93    console.log('Client #%d error: %s', thisId, e.message);
 94  });
 95});
 96
 97fs.mkdir(__dirname + '/uploaded', function(error) {
 98  // ignore errors, most likely means directory exists
 99  console.log('Uploaded files will be saved to %s/uploaded.', __dirname);
100  console.log('Remember to wipe this directory if you upload lots and lots.');
101  app.listen(8080);
102  console.log('Listening on http://localhost:8080');
103});