如何在新的 Windows 终端中检测是否 运行?

How to detect if running in the new Windows Terminal?

Windows 终端预览的一项即将推出的功能是它具有完整的表情符号支持:

相比于:

在 Node.js 中,如何检测我是否 运行 在被 Windows 终端而不是其 "naked" 变体包裹的终端中?是否有我可以提取的环境变量或我可以做的同步测试?

您可以检查设置为 v4 UUID 的 WT_SESSION 环境变量:https://github.com/microsoft/terminal/issues/1040

如果您正在寻找一种快速而粗略的检查方法,这应该可行:

!!process.env.WT_SESSION

您还可以使用更复杂的方法,利用 is-uuid, is-wslprocess.platform:

import isUUID from 'is-uuid';
import isWsl from 'is-wsl';

const isWindowsTerminal = (process.platform === "win32" || isWsl) && isUUID.v4(process.env.WT_SESSION);

我更喜欢 https://github.com/microsoft/terminal/issues/6269 中的这种方法(在 PowerShell 中):

function IsWindowsTerminal ($childProcess) {
    if (!$childProcess) {
        return $false
    } elseif ($childProcess.ProcessName -eq 'WindowsTerminal') {
        return $true
    } else {
        return IsWindowsTerminal -childProcess $childProcess.Parent
    }
}

然后我在我的个人资料中使用它来打开,例如oh-my-posh.

$IsWindowsTerminal = IsWindowsTerminal -childProcess (Get-Process -Id $PID)
if($IsWindowsTerminal) {
    oh-my-posh --init --shell pwsh --config $HOME\Documents\mytheme.omp.json | Invoke-Expression
}