如何在Node中获得当前的TTY设备?



我正在尝试获取当前TTY/PTY设备的路径。

如果我在shell中运行tty,它告诉我当前TTY的设备,但如果我使用child_process运行tty,我得到一个错误。我也试过fs.readlinkSync('/proc/self/fd/0'),但它也不起作用。

我试过了:

luis@Iphone-47 ~ % tty
/dev/ttys003
luis@Iphone-47 ~ % node
Welcome to Node.js v19.7.0.
Type ".help" for more information.
> const cp = require('child_process')
undefined
> try { cp.execSync('tty') } catch (err) { console.log(err.stdout.toString()) }
not a tty
undefined
> 

是否有跨平台的方法来做到这一点?

编辑:这可以在Python中工作,那么为什么不能在Node中呢?

luis@Iphone-47 ~ % python3
Python 3.9.1 (v3.9.1:1e5d33e9b9, Dec  7 2020, 12:10:52) 
[Clang 6.0 (clang-600.0.57)] on darwin
Type "help", "copyright", "credits" or "license" for more information.
>>> import os
>>> os.system('tty')
/dev/ttys001
0
>>> 

好的,我在GitHub上阅读了一个很长的问题后发现了它。

技巧是设置stdio继承stdin,并管道stdoutstderr:

const cp = require('child_process');
const ttyPath = cp.execSync('tty', {
stdio: [
'inherit',
'pipe',
'pipe'
]
}).toString().trim();

最新更新