假设在 Windows 机器上运行多个节点服务器的多个节点包/文件。 因此,我需要来自节点服务器的文件的所有信息(节点包/文件的完整路径、端口、主机、pid、ppid)正在计算机上工作/运行(node.exe)。
示例:机器上运行两个node.exe。两者都从不同的目的地运行(第一个从
"C:\Users\kuldeep.singh\Desktop\porting\v1\node1\index.js"
,另一个从"C:\Users\kuldeep.singh\Desktop\porting\v2\node2\index.js"
),具有不同的 PPID。
我想用节点进程启动后的目的地路径来过滤唯一的节点进程。
我得到了所有详细信息,例如:
[ { port: 3400,
pid: 27200,
ppid: 27168,
name: 'node.exe',
cmd: 'node index.js',
bin: 'C:\\Program Files\\nodejs\\node.exe' } ]
但是我无法获取运行node.exe 文件的目标路径(如(
"C:\Users\kuldeep.singh\Desktop\porting\v1\node1\index.js"
))。
目前,我正在使用
path
和 find-process
节点模块。
提供解决方案时请考虑windows机器
这应该适用于检查是否有任何
node.exe myscript.js
正在运行(或任何带有命令行的 .exe)。这个答案来自混合如何查看系统上当前正在运行哪些 Node.js 脚本?,如何找出正在运行的程序的命令行参数?和如何获取进程的命令行信息PowerShell 或 C#。
在 powershell 中运行以下任一命令,Get-WMIObject 将被 Get-CimInstance 取代,但两者都适用于 Win 11:
Get-WmiObject Win32_Process -Filter "name = 'node.exe'" | where {$_.CommandLine -match "script.js" } | select CommandLine
或:
Get-CimInstance Win32_Process -Filter "name = 'node.exe'" | where {$_.CommandLine -match "script.js" } | select CommandLine
如果进程处于活动状态并具有匹配的命令参数,您将看到类似于以下示例的响应,它们将反映调用时的行:
CommandLine
-----------
node script.js
或:
CommandLine
-----------
"C:\Program Files\nodejs\node.exe" D:\Data\myscript\script.js
如果没有,您将返回命令提示符,但没有任何输出。我们可以在一个非常基本的脚本中使用它来测试事物,复制/粘贴并另存为
testrunning.ps1
:
# Usage testrunning.ps1 exename searchstring
# testrunning.ps1 foo.exe bar
# testrunning.ps1 "foo.exe" "bar foo bar"
param([string]$exename,$searchstring)
# Capture output
$test = Get-CimInstance Win32_Process -Filter "name = `"$exename`"" | where {$_.CommandLine -match "$searchstring" } | select CommandLine | Out-String
# Very basic test, $test is empty if search returns nothing
# We use -notmatch so we can remove the else section if
# we are only concerned about it not running
if ($test -notmatch $searchstring) {
echo "`'$exename $searchstring`' Not Running"
# We could do something here like restart a script or send a warning
}else{
echo $test
echo "`'$exename $searchstring`' is Running"
}
然后运行
.\testprocess.ps1 "node.exe" "server.js"
(这测试我的 TamperDAV 服务器)。
我得到:
CommandLine
-----------
"C:\Program Files\nodejs\node.exe" D:\Data\OneDrive\TamperDAV\server.js
'node.exe server.js' is Running
一个限制/缺点是您无法检查多个参数(例如,我的 TamperDAV 命令是
node.exe server.js %*
),但是,只要您测试的匹配是唯一的,这就不应该成为问题。在OP的情况下...
testprocess.ps1 "node.exe" "C:\Users\kuldeep.singh\Desktop\porting\v1\node1\index.js"
应该可以解决问题。 😎
通过使用以下代码,您可以找到目录/文件
console.log(__filename);
console.log(__dirname);