coreybutler / node-windows

Windows support for Node.JS scripts (daemons, eventlog, UAC, etc).
Other
2.83k stars 356 forks source link

list + kill behavior not as reliable in 1.x-beta, as in 0.1.11 #303

Open unquietwiki opened 2 years ago

unquietwiki commented 2 years ago

I'm trying to modernize some code for work, and noticed a lot of .list & .kill commands to find & terminate errant processes. It appears in the latest 1.x beta, the list function doesn't correctly pass PIDs in a way the kill function understands. I've provided some obfuscated code for your review. Thanks!

const wincmd = require('node-windows')
const userprogramProc = ["userprogram.exe", "userprogram2.exe"]
// returns the pids of exes that match userprogramProc
async function checkuserprogramProcesses(svc){
    let svcPromise
    if (svc) {
        svcPromise = Promise.resolve(svc)
    } else {
        svcPromise = new Promise((resolve) => wincmd.list((svc) => resolve(svc)))
    }
    let pids = await svcPromise.then(svc => {
        const processes = _.filter(svc, (p) => userprogramProc.includes(p.ImageName))
        return _.map(processes, 'PID')
    })
    return pids
}
async function closeuserprogramProcesses (){
    await closeProcessIfRunning("otherprogram.exe", false)
    let pids = await checkuserprogramProcesses()
    return Promise.map(pids, (pid) => new Promise((resolve) => wincmd.kill(pid, true, () => {
                logger.info('closed userprogram process')
                return resolve()
            })), {concurrency: 2})
}