Search code examples
node.jstty

How can I connect a node.js child process to a specific tty device?


I want to spawn a node.js child process and attach it's stdio to a specifc tty, let's say /dev/ttyS0. I know about { stdio: 'inherit' }, but I don't want to connect the child to the same tty as the parent. I know about pty.js but I don't want to have it connect to a psudotty, I want it to connect to a REAL tty. I have tried piping the child process's stdio to a tty that I opened with the serialport module:

var SerialPort = require('serialport');
var tty = new SerialPort('/dev/ttyS0');
var cp = require('child_process');
var myprocess = cp.spawn('myprocess');
myprocess.stdout.pipe(tty);
myprocess.stderr.pipe(tty);
tty.pipe(myprocess.stdin);

but it doesn't work for processes that need access to a real tty, like sudo for example. I don't actually plan to use sudo specifically however.


Solution

  • I did end up finding out how to do this, originally with the tty module, but I later discovered that any old WriteStream and ReadStream will do, not just tty.Read/WriteStream. Initially I tried creating a ReadStream and WriteStream by opening the file twice, but that didn’t work as I only needed to open the file once in r+ mode. This is what I did:

    var ttyFd = require('fs').open('/dev/ttyS0', 'r+');
    require('child_process').spawn('myprocess', [], {stdio: [ttyFd, ttyFd, ttyFd]});
    

    Now when I put the tty command in cp.spawn() it prints the name of the terminal to the terminal. Commands like sudo and man that need direct terminal access work flawlessly.