forked from SheetJS/sheetjs
-
Notifications
You must be signed in to change notification settings - Fork 0
/
hapi.js
66 lines (60 loc) · 1.98 KB
/
hapi.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
/* xlsx.js (C) 2013-present SheetJS -- http://sheetjs.com */
var Hapi = require('hapi'), server = new Hapi.Server();
var logit = require('./_logit');
var Worker = require('tiny-worker');
var fs = require('fs');
var data = "a,b,c\n1,2,3".split("\n").map(x => x.split(","));
function get_data(req, res, type) {
var work = new Worker('worker.js');
work.onmessage = function(e) {
if(e.data.err) console.log(e.data.err);
return res(e.data.data);
};
work.postMessage({action:"write", type:type, data:data});
}
function get_file(req, res, file) {
var work = new Worker('worker.js');
work.onmessage = function(e) {
fs.writeFileSync(file, e.data.data, 'binary');
return res("wrote to " + file + "\n");
};
work.postMessage({action:"write", file:file, data:data});
}
function post_file(req, res, file) {
var work = new Worker('worker.js');
work.onmessage = function(e) {
data = e.data.data;
return res("read from " + file + "\n");
};
work.postMessage({action:"read", file:file});
}
function post_data(req, res, type) {
var keys = Object.keys(req.payload), k = keys[0];
post_file(req, res, req.payload[k].path);
}
var port = 7262;
server.connection({ host:'localhost', port: port});
server.route({ method: 'GET', path: '/',
handler: function(req, res) {
logit(req.raw.req, req.raw.res);
if(req.query.t) get_data(req, res, req.query.t);
else if(req.query.f) get_file(req, res, req.query.f);
else res('Forbidden').code(403);
}});
server.route({ method: 'POST', path: '/',
config:{payload:{ output: 'file', parse: true, allow: 'multipart/form-data'}},
handler: function(req, res) {
logit(req.raw.req, req.raw.res);
if(req.query.f) return post_file(req, res, req.query.f);
return post_data(req, res);
}});
server.route({ method: 'POST', path: '/file',
handler: function(req, res) {
logit(req.raw.req, req.raw.res);
if(req.query.f) return post_file(req, res, req.query.f);
return post_data(req, res);
}});
server.start(function(err) {
if(err) throw err;
console.log('Serving HTTP on port ' + port);
});