Skip to content

Instantly share code, notes, and snippets.

@svnlto
Last active August 17, 2016 05:12
Show Gist options
  • Save svnlto/6cdc32d74a28b02ff3f51144730d3b86 to your computer and use it in GitHub Desktop.
Save svnlto/6cdc32d74a28b02ff3f51144730d3b86 to your computer and use it in GitHub Desktop.
import IO from 'socket.io-client';
import Promise from 'bluebird';
import streamToPromise from 'stream-to-promise';
import fs from 'fs';
const io = IO('http://localhost:3000', {
reconnect: true
});
export default (() => {
io.on('error', (err) => {
console.log('error: ', err);
});
io.on('connect', () => {
console.log('>>>>>>> socket connected');
const apiInit = (file_info) => {
return new Promise((resolve) => {
io.emit('upload', {
upload_phase: 'start',
file_size: file_info.size
}, (res) => resolve(res));
});
};
const apiFinish = () => {
return new Promise((resolve) => {
io.emit('upload', {
upload_phase: 'finish'
}, (res) => resolve(res));
});
};
const uploadChunk = (start, end, chunk, snapshot_id) => {
const opts = {
upload_phase: 'transfer',
start_offset: start,
end_offset: end,
snapshot_id: snapshot_id,
chunk: chunk
};
return new Promise((resolve) => {
io.emit('upload', opts, (res) => resolve(res));
});
};
const uploadChain = (buffer, res) => {
if (res.start_offset === res.end_offset) { return res; }
const chunk = buffer.slice(res.start_offset, res.end_offset);
return uploadChunk(res.start_offset, res.end_offset, chunk, res.snapshot_id)
.then((res) => uploadChain(buffer, res));
};
const apiUpload = (args) => {
const fileInfo = fs.statSync(args.file_path);
const stream = fs.createReadStream(args.file_path, { defaultEncoding: 'utf8' });
return Promise.resolve(streamToPromise(stream))
.then((buffer) => [buffer, apiInit(fileInfo, args.snapshot_id)])
.spread((buffer, res) => uploadChain(buffer, res))
.then(() => apiFinish());
};
return apiUpload({
snapshot_id: '57ac622940d0c1788936c39b',
file_path: __dirname + '/test.img' //path to file to upload
})
.then((res) => {
console.log('res: ', res);
})
.catch((e) => {
console.error(e);
});
});
})();
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment