Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Nodejs - Get environment variables of running process

I am writing an extension for vscode, and I need to get the environment variables of a process that is already running. But I wasn't able to find a way to do it.

I know how to do it in python using psutil:

for proc in psutil.process_iter(attrs=['name', 'exe']):
    if proc.info['name'].lower() == 'SomeProcess.exe'.lower():
        return proc.environ()

Is there something similar for javascript/nodejs?

like image 799
psclkhoury Avatar asked Dec 23 '22 21:12

psclkhoury


2 Answers

You can use child_process module to spawn a terminal and execute the following commands wrt platform and get the variables, parse & use or write a native node module to access the proper APIs of each platform and get the output.

Windows (Using powershell, 2019 is the PID )

(Get-Process -id 2019).StartInfo.EnvironmentVariables

Linux

tr '\0' '\n' < /proc/2019/environ

Mac

ps eww -o command 2019  | tr ' ' '\n'

Thanks to https://serverfault.com/a/66366 & https://stackoverflow.com/a/28193753/12167785 & https://apple.stackexchange.com/a/254253 & https://stackoverflow.com/a/11547409/12167785 & https://stackoverflow.com/a/18765553/12167785

like image 90
Sudhakar Ramasamy Avatar answered Dec 28 '22 10:12

Sudhakar Ramasamy


Combining with @SudhakarRS's answer:

var child = require('child_process').execFile('powershell', [ 
    '(Get-Process SomeProcess).StartInfo.EnvironmentVariables' 
], function(err, stdout, stderr) { 
    console.log(stdout);
}); 

If you want to debug it, make sure you peek at err and stderr.

Replacing SomeProcess with notepad works for me, but using notepad.exe does not.

On powershell you can get the processes with a particular name using Get-Process [process name].

So, for example, if I have 4 instances of notepad running and do Get-Process notepad, I see this:

Processes

You can get the process IDs with (Get-Process notepad).Id which returns:

Image

You could use the same code to choose the ID:

var child = require('child_process').execFile(
    'powershell',
    ['(Get-Process notepad).Id'],
    function(err, stdout, stderr) { 
        var ids = stdout.split("\r\n");
        ids.pop(); //remove the blank string at the end
        console.log(ids);
    }
);

^ which returns:

Return

If you just want to grab the first process with a name, it's:

(Get-Process notepad)[0].StartInfo.EnvironmentVariables

^ obviously replace notepad with your process name.

like image 30
user1274820 Avatar answered Dec 28 '22 08:12

user1274820