forked from Automattic/node-canvas
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathserver.js
More file actions
104 lines (83 loc) · 2.34 KB
/
Copy pathserver.js
File metadata and controls
104 lines (83 loc) · 2.34 KB
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
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
/**
* Module dependencies.
*/
var express = require('express')
, Canvas = require('../lib/canvas')
, Image = Canvas.Image
, bodyParser = require('body-parser')
, app = express();
// Config
app.set('views', __dirname + '/views');
app.set('view engine', 'jade');
// Middleware
app.use(bodyParser.json());
app.use(express.static(__dirname + '/public'));
// Routes
app.get('/', function(req, res){
res.render('tests');
});
function testFn(req){
// Normalize state.png as ./public/state.png
// no good way around this at the moment
req.body.fn = req.body.fn
.replace("'state.png'", "'" + __dirname + "/public/state.png'")
.replace("'face.jpeg'", "'" + __dirname + "/public/face.jpeg'")
.replace("'star.png'", "'" + __dirname + "/public/star.png'");
// Do not try this at home :)
return eval('(' + req.body.fn + ')');
}
function createCanvas(req, type){
var width = req.body.width
, height = req.body.height;
return new Canvas(width, height, type);
}
app.post('/render', function(req, res, next){
var fn = testFn(req)
, canvas = createCanvas(req)
, ctx = canvas.getContext('2d')
, start = new Date;
function done(){
var duration = new Date - start;
canvas.toDataURL(function(err, str){
res.send({ data: str, duration: duration });
});
}
2 == fn.length
? fn(ctx, done)
: fn(ctx), done();
});
app.post('/pdf', function(req, res, next){
req.body = JSON.parse(req.body.json);
var fn = testFn(req)
, canvas = createCanvas(req, 'pdf')
, ctx = canvas.getContext('2d');
function done(){
res.writeHead(200, {'Content-Type' : 'application/pdf'});
res.write(canvas.toBuffer());
res.end();
}
2 == fn.length
? fn(ctx, done)
: fn(ctx), done();
});
app.post('/jpeg', function(req, res, next){
var fn = testFn(req)
, canvas = createCanvas(req)
, ctx = canvas.getContext('2d');
function done(){
var stream = canvas.jpegStream();
var buffers = [];
stream.on('data', function (chunk) {
buffers.push(chunk);
});
stream.on('end', function() {
res.send({data: 'data:image/jpeg;base64,' + Buffer.concat(buffers).toString('base64')});
});
}
2 == fn.length
? fn(ctx, done)
: fn(ctx), done();
});
var port = parseInt(process.argv[2] || '4000', 10);
app.listen(port);
console.log('Test server listening on port %d', port);