We're trying to convert the function PSRunner to a TypeScript function:
export function PSRunner(commands: string[]) {
const self: {
out: string[]
err: string[]
} = this
const results: { command: string; output: any; errors: any }[] = []
const child = spawn('powershell.exe', ['-Command', '-'])
child.stdout.on('data', function (data) {
self.out.push(data.toString())
})
child.stderr.on('data', function (data) {
self.err.push(data.toString())
})
commands.forEach(function (cmd) {
self.out = []
self.err = []
child.stdin.write(cmd + '\n')
results.push({ command: cmd, output: self.out, errors: self.err })
})
child.stdin.end()
return results
}
I'm a bit confused with how this
works. An object literal is created called self
. This is then populated with data coming from child.stdout
and child.stderr
. Later on, in the foreach
, the this.out
and this.err
are set to an empty array again.
How can result
then hold the values related to that one specific command? I would try to use a fat arrow function to avoid having to use this
, but in this case it might be required?
There are also some TS errors with regards to not use any
. But I would like to understand first how this works. Thank you for any clarifications.