-
Notifications
You must be signed in to change notification settings - Fork 4
/
Copy pathindex.js
59 lines (51 loc) · 1.5 KB
/
index.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
var printer = require('printer'),
express = require('express'),
printerExpress = express(),
bodyParser = require('body-parser'),
extend = require('util')._extend,
http = require('http'),
fs = require('fs'),
tmp = require('tmp');
function download(url, dest, cb) {
var file = fs.createWriteStream(dest);
var request = http.get(url, function(response) {
response.pipe(file);
file.on('finish', function() {
file.close(cb); // close() is async, call cb after close completes.
});
}).on('error', function(err) { // Handle errors
fs.unlink(dest); // Delete the file async. (But we don't check the result)
if (cb) cb(err.message);
});
};
var printerMiddleware = function (req, res, next) {
if (!req.printer) {
req.printer = printer;
}
next();
};
printerExpress.use(bodyParser.json());
printerExpress.use(printerMiddleware);
printerExpress.get('/printers', function (req, res) {
res.json(req.printer.getPrinters());
});
printerExpress.post('/jobs', function (req, res) {
var job = req.body;
var callbacks = {
success: function (jobID) {
res.status(201).json({ job_id: jobID });
},
error: function (error) {
res.status(400).json({ error: error.message });
}
}
if (job.url) {
job.filename = tmp.tmpNameSync();
download(job.url, job.filename, function () {
req.printer.printFile(extend(job, callbacks));
});
} else {
req.printer.printDirect(extend(job, callbacks));
}
});
module.exports = printerExpress;