-
Notifications
You must be signed in to change notification settings - Fork 2
/
Copy pathcli.js
executable file
·63 lines (51 loc) · 2.02 KB
/
cli.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
#!/usr/bin/env node
const fs = require('fs');
const path = require('path');
const program = require('commander');
const optim = require('./optim');
const package = require('./package.json');
const SIZES = ['B', 'KB', 'MB', 'GB', 'TB', 'PB', 'EB', 'ZB', 'YB'];
let inputValue;
program
.version(package.version)
.name('lottie-optim')
.option('-p, --precision <number>', 'Round numbers to a number of decimal places to reduce filesize', parseInt, 2)
.option('-o, --out <file>', 'Output file, without this option the original file with be overridden')
.arguments('<file>')
.action(input => (inputValue = input))
.parse(process.argv);
if (inputValue == null) {
console.error('No lottie JSON file specified.');
process.exit(1);
}
const inputPath = path.resolve(inputValue);
const outputValue = program.out != null ? program.out : inputValue;
const outputPath = path.resolve(outputValue);
try {
if (!fs.existsSync(inputPath))
throw new Error(`Could not find or access ${inputValue}, please check that it exists.`);
const content = fs.readFileSync(inputPath, 'utf8');
if (content == null) throw new Error(`Could not open ${inputValue}`);
const {output, inputBytes, outputBytes, nodesDeleted} = optim(content, program.precision);
fs.writeFileSync(outputPath, output);
console.log(`Optimised Lottie JSON written to ${outputValue}`);
console.log(`Input: ${readableBytes(inputBytes)}`);
console.log(`Output: ${readableBytes(outputBytes)}`);
console.log(`Reduction: ${readableBytes(outputBytes - inputBytes)} (${percent(outputBytes / inputBytes - 1)})`);
} catch (error) {
console.error(error);
process.exit(1);
}
function readableBytes(bytes) {
let sign = '';
if (bytes < 0) {
sign = '-';
bytes = Math.abs(bytes);
}
const index = bytes == 0 ? 0 : Math.floor(Math.log(bytes) / Math.log(1024));
const number = bytes == 0 ? 0 : new Number((bytes / Math.pow(1024, index)).toFixed(2));
return `${sign}${number} ${SIZES[index]}`;
}
function percent(value) {
return `${Math.round(value * 100)}%`;
}