-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathindex.js
More file actions
74 lines (66 loc) · 1.72 KB
/
index.js
File metadata and controls
74 lines (66 loc) · 1.72 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
'use strict';
const { spawn } = require('child_process');
const path = require('path');
const libbpgBin = require('libbpg-bin');
// set EventEmitters to unlimited
process.stdout.setMaxListeners(Infinity);
process.stderr.setMaxListeners(Infinity);
const flags = {
bpgenc: {
qp: '-q',
cfmt: '-f',
color_space: '-c',
bit_depth: '-b',
lossless: '-lossless',
encoder: '-e',
level: '-m',
alphaq: '-alphaq',
premul: '-premul',
limitedrange: '-limitedrange',
hash: '-hash',
keepmetadata: '-keepmetadata',
verbose: '-v'
},
bpgdec: {
information: '-i',
bit_depth: '-b'
}
};
function configToArgs(config, type) {
return Object
.keys(config)
.map(key => {
if (!flags[type][key]) {
return;
}
let args = [flags[type][key]];
typeof config[key] !== 'boolean' && args.push(config[key]);
return args;
})
.reduce((all, opt) => all.concat(opt), [])
.filter(chunk => chunk !== undefined);
}
function exportWrapper(type) {
return function(input, output, config = {}, cb) {
return new Promise((resolve, reject) => {
if (!input || !output) {
(cb || reject)(new Error('Invalid input or output filepath.'));
}
let args = ['-o', output].concat(configToArgs(config, type)).concat(input);
const child = spawn(libbpgBin[type], args);
child.on('exit', code => {
if (code !== 0) {
(cb || reject)(new Error(`${type} exited with non-zero code.`));
} else {
(cb || resolve)();
}
});
child.stdout.pipe(process.stdout);
child.stderr.pipe(process.stderr);
});
};
}
module.exports = {
encode: exportWrapper('bpgenc'),
decode: exportWrapper('bpgdec')
};