Can't get node to exit fully after using pty / process.stdin / process.stdout

782 Views Asked by At

I'm struggling to get the behavior I'd like from node and node-pty. Node doesn't seem to fully exit after executing this code. Looking for hints on what I'm missing. I've distilled things down to a small example to demonstrate. When you execute the code, it will spawn /bin/sh. Once you exit that shell, it will spawn a second /bin/sh (in the same manner). Once you exit that shell, node hangs.

let pty = require('node-pty');

main();

async function main() {
    let ptyProcess;

    console.log('Starting session 1');
    ptyProcess = pty.spawn('/bin/sh');
    await interact(ptyProcess);
    ptyProcess.kill();

    console.log('Starting session 2');
    ptyProcess = pty.spawn('/bin/sh');
    await interact(ptyProcess);
    ptyProcess.kill();

    console.log('Why won\'t I exit?');
}

function interact(ptyProcess) { // Allow user interaction from here on out
    return new Promise((resolve, reject) => {

        process.stdout.on('resize', () => {
            ptyProcess.resize(process.stdout.columns, process.stdout.rows);
        });

        process.stdin.on('data', data => {
            ptyProcess.write(data);
        });

        ptyProcess.on('data', data => {
            process.stdout.write(data);
        });

        ptyProcess.on('close', () => {
            console.log('Closing...');
            resolve();
        })
    });
}

Example session:

MacBook-Pro:src mtwomey$ node demo.js
Starting session 1
sh-3.2$ exit
exit
exit
Closing...
Starting session 2
sh-3.2$ exit
exit
exit
Closing...
Why won't I exit?


[node remains running / open here]
1

There are 1 best solutions below

1
On

It turns out this is not at all related to node-pty. It's straight process.stdin.

process.stdin.unref() is what I needed.