This repository has been archived by the owner on Nov 2, 2020. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 1
/
index.js
74 lines (63 loc) · 1.86 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
const { spawn } = require('child_process')
// Defaults for image thumbnails
const imageOptions = {
width: 100,
height: 100,
preserveAspectRatio: true
}
// Defaults for video thumbnails
const videoOptions = {
width: 100,
height: -1
}
const VIDEO_TYPE = 'video'
const IMAGE_TYPE = 'image'
/**
* A pure function to generate thumbnail for an image or a video.
*
* @param {string} source path to source image file
* @param {string} destination path to destination folder
* @param {object} options configuration options
* @param {string} type video|image
*/
const thumbGenerator = (source, destination, options, type) =>
new Promise((resolve, reject) => {
if (!source || !destination) {
reject(new Error('Source or destination path missing'))
}
// console.log(options)
let convert
if (type === IMAGE_TYPE) {
convert = spawn(
'convert',
[ source,
'-thumbnail',
`${options.width}x${options.height}${options.preserveAspectRatio ? '' : '!'}`,
destination
])
} else {
convert = spawn(
'ffmpeg',
[ `-i ${source}`,
`-vf "thumbnail,scale=${options.width}:${options.height}" -vframes 1`,
'-nostdin -y',
destination
], { shell: true })
}
// convert.stdout.on('data', data => console.log(data))
// convert.stderr.on('data', data => console.error(data))
convert.on('exit', code => {
if (code !== 0) {
reject(new Error('Non-zero exit code'))
}
resolve()
})
})
const forImage = (source, destination, options) =>
thumbGenerator(source, destination, Object.assign({}, imageOptions, options), IMAGE_TYPE)
const forVideo = (source, destination, options) =>
thumbGenerator(source, destination, Object.assign({}, videoOptions, options), VIDEO_TYPE)
module.exports = {
forImage,
forVideo
}