-
Notifications
You must be signed in to change notification settings - Fork 0
/
index.js
90 lines (76 loc) · 2.26 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
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
// Import Node.js Dependencies
const { Readable } = require("node:stream");
const fs = require("node:fs");
// Import Third-Party Dependencies
const { familySync, MUSL } = require("detect-libc");
// CONSTANTS
const { arch, platform } = process;
const compiler = familySync() === MUSL ? "musl" : "";
const kPlatform = `${platform}${compiler}-${arch}`;
const binaryPaths = [
`@myunisoft/heif-converter.${kPlatform}/converter.node`,
`./src/build/Release/converter.node`
];
let lib = null;
const errors = [];
for (const binaryPath of binaryPaths) {
try {
lib = require(binaryPath);
}
catch (error) {
errors.push(error);
}
}
if (lib === null) {
const errorMessages = errors.map((error) => error.message);
errorMessages.unshift(`You cannot use heif-converter on the following platform: ${kPlatform}`);
throw new Error(errorMessages.join("\n"));
}
async function getBufferFromInput(input) {
let stream = input;
if (typeof input === "string") {
stream = fs.createReadStream(input);
}
else if (input instanceof Buffer) {
stream = Readable.from(stream);
}
const buffers = [];
for await (const chunk of stream) {
buffers.push(chunk);
}
return Buffer.concat(buffers);
}
module.exports = {
async toJpeg(input, options = { quality: 75 }) {
const buffer = await getBufferFromInput(input);
return await new Promise((res, rej) => lib.toJpeg(
buffer,
undefined,
options,
(err, data) => (err ? rej(err) : res(data))
));
},
async toPng(input, options = { compression: 1 }) {
const buffer = await getBufferFromInput(input);
return await new Promise((res, rej) => lib.toPng(
buffer,
undefined,
options,
(err, data) => (err ? rej(err) : res(data))
));
},
async extract(input) {
const buffer = await getBufferFromInput(input);
const ids = lib.extractIds(buffer);
return ids.map((id) => {
return {
toJpeg: (options = { quality: 75 }) => new Promise((res, rej) => {
lib.toJpeg(buffer, id, options, (err, data) => (err ? rej(err) : res(data)));
}),
toPng: (options = { compression: 1 }) => new Promise((res, rej) => {
lib.toPng(buffer, id, options, (err, data) => (err ? rej(err) : res(data)));
})
};
});
}
};