-
Notifications
You must be signed in to change notification settings - Fork 15
/
Copy pathlib.js
227 lines (204 loc) · 6.56 KB
/
lib.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
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
'use strict'
const cp = require('child_process')
const EOL = require('os').EOL
const isStream = require('is-stream')
function writeStdIn(proc, data, encoding) {
// console.log('write stdin', data)
proc.stdin.write(data, encoding)
proc.stdin.write(EOL, encoding)
}
function close(proc) {
let errHandler
return new Promise((resolve, reject) => {
errHandler = (err) => {
reject(new Error(`Could not write to stdin: ${err.message}`))
}
proc.once('close', resolve)
proc.stdin.once('error', errHandler)
writeStdIn(proc, '-stay_open')
writeStdIn(proc, 'false')
})
.then(() => {
proc.stdin.removeListener('error', errHandler)
})
}
function isString(s) {
return (typeof s).toLowerCase() === 'string'
}
function isObject(o) {
return (typeof o).toLowerCase() === 'object' && o !== null
}
/**
* Get arguments. Split by new line to write to exiftool
*/
function getArgs(args, noSplit) {
if(!(Array.isArray(args) && args.length)) {
return []
}
return args
.filter(isString)
.map(arg => `-${arg}`)
.reduce((acc, arg) =>
[].concat(acc, noSplit ? [arg] : arg.split(/\s+/))
, [])
}
/**
* Write command data to the exiftool's stdin.
* @param {ChildProcess} process - exiftool process executed with -stay_open True -@ -
* @param {string} command - which command to execute
* @param {string} commandNumber - text which will be echoed before and after results
* @param {string[]} args - any additional arguments
* @param {string[]} noSplitArgs - arguments which should not be broken up like args
* @param {string} encoding - which encoding to write in. default no encoding
*/
function execute(proc, command, commandNumber, args, noSplitArgs, encoding) {
const extendedArgs = getArgs(args)
const extendedArgsNoSplit = getArgs(noSplitArgs, true)
command = command !== undefined ? command : ''
const allArgs = [].concat(
extendedArgsNoSplit,
extendedArgs,
['-json', '-s'],
[
command,
'-echo1',
`{begin${commandNumber}}`,
'-echo2',
`{begin${commandNumber}}`,
'-echo4',
`{ready${commandNumber}}`,
`-execute${commandNumber}`,
]
)
if (process.env.DEBUG) {
console.log(JSON.stringify(allArgs, null, 2))
}
allArgs.forEach(arg => writeStdIn(proc, arg, encoding))
}
let currentCommand = 0
function genCommandNumber() {
return String(++currentCommand)
}
function executeCommand(proc, stdoutRws, stderrRws, command, args, noSplitArgs, encoding) {
const commandNumber = genCommandNumber()
if (proc === process) { // debugging
execute(proc, command, commandNumber, args, noSplitArgs, encoding)
return Promise.resolve({ data: 'debug', error: null })
}
let dataFinishHandler
let errFinishHandler
let dataErr
let errErr
const dataPromise = new Promise((resolve, reject) => {
dataFinishHandler = () => {
reject(new Error('stdout stream finished before operation was complete'))
}
stdoutRws.once('finish', dataFinishHandler)
stdoutRws.addToResolveMap(commandNumber, resolve)
}).catch(error => { dataErr = error })
const errPromise = new Promise((resolve, reject) => {
errFinishHandler = () => {
reject(new Error('stderr stream finished before operation was complete'))
}
stderrRws.once('finish', errFinishHandler)
stderrRws.addToResolveMap(commandNumber, resolve)
}).catch(error => { errErr = error })
execute(proc, command, commandNumber, args, noSplitArgs, encoding)
return Promise.all([
dataPromise,
errPromise,
])
.then((res) => {
stderrRws.removeListener('finish', errFinishHandler)
stdoutRws.removeListener('finish', dataFinishHandler)
if (dataErr && !errErr) {
throw dataErr
} else if (errErr && !dataErr) {
throw errErr
} else if (dataErr && errErr) {
throw new Error('stdout and stderr finished before operation was complete')
}
return {
data: res[0] ? JSON.parse(res[0]) : null,
error: res[1] || null,
}
})
}
function isReadable(stream) {
return isStream.readable(stream)
}
function isWritable(stream) {
return isStream.writable(stream)
}
/**
* Spawn exiftool.
* @param {string} bin Path to the binary
* @param {object} [options] options to pass to child_process.spawn method
* @returns {Promise.<ChildProcess>} A promise resolved with the process pointer, or rejected on error.
*/
function spawn(bin, options) {
const echoString = Date.now().toString()
const proc = cp.spawn(bin, ['-echo2', echoString, '-stay_open', 'True', '-@', '-'], options)
if (!isReadable(proc.stderr)) {
killProcess(proc)
return Promise.reject(new Error('Process was not spawned with a readable stderr, check stdio options.'))
}
return new Promise((resolve, reject) => {
const echoHandler = (data) => {
const d = data.toString().trim()
// listening for echo2 in stderr (echo and echo1 won't work)
if (d === echoString) {
resolve(proc)
} else {
reject(new Error(`Unexpected string on start: ${d}`))
}
}
proc.stderr.once('data', echoHandler)
proc.once('error', reject)
})
}
function checkDataObject(data) {
return data === Object(data) && !Array.isArray(data)
}
function mapDataToTagArray(data, array) {
const res = Array.isArray(array) ? array : []
Object
.keys(data)
.forEach(tag => {
const value = data[tag]
if (Array.isArray(value)) {
value.forEach((v) => {
const arg = `${tag}=${v}`
res.push(arg)
})
} else {
res.push(`${tag}=${value}`)
}
})
return res
}
/**
* Use process.kill on POSIX or terminate process with taskkill on Windows.
* @param {ChildProcess} proc Process to terminate
*/
function killProcess(proc) {
if (process.platform === 'win32') {
cp.exec(`taskkill /t /F /PID ${proc.pid}`)
} else {
proc.kill()
}
}
module.exports = {
spawn,
close,
executeCommand,
checkDataObject,
mapDataToTagArray,
getArgs,
execute,
isString,
isObject,
isReadable,
isWritable,
killProcess,
}