From 78f4ef504682af1b25da2bfacdc04df89ca8eb2f Mon Sep 17 00:00:00 2001 From: Sebastian Hildebrandt Date: Tue, 5 Feb 2019 10:42:57 +0100 Subject: [PATCH] powerShell optimizatio error handling --- lib/util.js | 70 ++++++++++++++++++++++++++++++++--------------------- 1 file changed, 43 insertions(+), 27 deletions(-) diff --git a/lib/util.js b/lib/util.js index 8eb7f14..25b8375 100644 --- a/lib/util.js +++ b/lib/util.js @@ -217,39 +217,55 @@ function getWmic() { } function powerShell(cmd) { + + // helper function + function dispose(child) { + return new Promise((resolve, reject) => { + child.stdin.write('exit' + os.EOL); + process.nextTick(() => { + child.stdin.end() + child.kill(); + resolve(); + }); + }) + } + + let result = ''; + return new Promise((resolve, reject) => { + process.nextTick(() => { - let result = ''; - const child = spawn('powershell.exe', ['-NoLogo', '-InputFormat', 'Text', '-NoExit', '-ExecutionPolicy', 'Unrestricted', '-Command', '-'], { - stdio: 'pipe' - }); - - if (child) { - child.stdout.on('data', function (data) { - result = result + data.toString('utf8'); - }); - child.stderr.on('data', function (data) { - child.kill(); - reject(data); - }); - child.on('close', function () { - child.kill(); - resolve(result); - }); - child.on('error', function () { - child.kill(); - resolve(result); + try { + const child = spawn('powershell.exe', ['-NoLogo', '-InputFormat', 'Text', '-NoExit', '-ExecutionPolicy', 'Unrestricted', '-Command', '-'], { + stdio: 'pipe' }); - try { - child.stdin.write(cmd + '\n'); - child.stdin.end(); - } catch (e) { - reject(result) + if (child && child.pid) { + child.stdout.on('data', function (data) { + result = result + data.toString('utf8'); + }); + child.stderr.on('data', function (data) { + dispose(child).then(resolve(result)); + }); + child.on('close', function () { + dispose(child).then(resolve(result)); + ; + }); + child.on('error', function () { + dispose(child).then(resolve(result)); + }); + + try { + child.stdin.write(cmd + os.EOL); + } catch (e) { + dispose(child).then(resolve(result)); + } + } else { + resolve(result); } - } else { - reject(result); + } catch (e) { + resolve(result); } }); });