NODEJS process info - node.js

How to get the process name with a PID (Process ID) in Node.JS program, platform include Mac, Windows, Linux.
Does it has some node modules to do it?

Yes, built-in/core modules process does this:
So, just say var process = require('process'); Then
To get PID (Process ID):
if (process.pid) {
console.log('This process is your pid ' + process.pid);
}
To get Platform information:
console.log('This platform is ' + process.platform);
Note: You can only get to know the PID of child process or parent process.
Updated as per your requirements. (Tested On WINDOWS)
var exec = require('child_process').exec;
var yourPID = '1444';
exec('tasklist', function(err, stdout, stderr) {
var lines = stdout.toString().split('\n');
var results = new Array();
lines.forEach(function(line) {
var parts = line.split('=');
parts.forEach(function(items){
if(items.toString().indexOf(yourPID) > -1){
console.log(items.toString().substring(0, items.toString().indexOf(yourPID)));
}
})
});
});
On Linux you can try something like:
var spawn = require('child_process').spawn,
cmdd = spawn('your_command'); //something like: 'man ps'
cmdd.stdout.on('data', function (data) {
console.log('' + data);
});
cmdd.stderr.setEncoding('utf8');
cmdd.stderr.on('data', function (data) {
if (/^execvp\(\)/.test(data)) {
console.log('Failed to start child process.');
}
});

On Ubuntu Linux, I tried
var process = require('process'); but it gave error.
I tried without importing any process module it worked
console.log('This process is your pid ' + process.pid);
One more thing I noticed we can define name for the process using
process.title = 'node-chat'
To check the nodejs process in bash shell using following command
ps -aux | grep node-chat

cf official documentation https://nodejs.org/dist/latest-v10.x/docs/api/process.html#process_process_pid
the require is no more needed.
The good sample is :
console.log(`This process is pid ${process.pid}`);

Related

Nodejs - best way to know a service status [linux]

Do someone know the best way (or just a good one) to know a service status from a linux (centos, here) system ?
When i run this piece of code:
{ ... }
const { spawnSync } = require('child_process'),
ts3 = spawnSync('service teamspeak status | grep active'),
{ ... },
This throw me a ENOENT error. I got the same error from my windows system when I tried a simple dir command, I had to write a stupid cmd file named "dir.cmd" with the content "dir" in my system32 (or any dir in the path env variable) and replace
dir = spawnSync('dir'),
By
dir = spawnSync('dir.cmd'), //This file is now in a dir in the PATH env var
So, i think this is related to a no-auto-resolution of the files with a sh,cmd or something else extention
But this isn't working when I replace the "service" by a "service.sh" anyway (from the first piece of code)
So, maybe someone already did this before and can help me a bit ?
Thanks,
And have a nice day !
A couple of issues, first, when using spawn, you should pass the arguments withing an array. Second, you're trying to run two processes within one spawn.
Instead, you can break down two processes and use the stdout from the first process (service), as the stdin for the second one (grep). I believe this should do it:
const { spawn } = require('child_process');
const service = spawn('service', ['teamspeak', 'status']);
const grep = spawn('grep', ['active']);
service.stdout.on('data', (data) => {
grep.stdin.write(data);
});
service.stderr.on('data', (data) => {
console.error(`service stderr: ${data}`);
});
service.on('close', (code) => {
if (code !== 0) {
console.log(`ps process exited with code ${code}`);
}
grep.stdin.end();
});
grep.stdout.on('data', (data) => {
console.log(data.toString());
});
grep.stderr.on('data', (data) => {
console.error(`grep stderr: ${data}`);
});
grep.on('close', (code) => {
if (code !== 0) {
console.log(`grep process exited with code ${code}`);
}
});
Hope this helped.

Open apps using node.js spawn

I'm trying to do a little application with node.js that would run on mac and execute some commands.
I've successfully used spawn to run command lines such as xcodebuild, but xcrun doesn't seems to work when I try to open the iOS Simulator.
I can open on terminal by typing:
xcrun instruments -w 'iPhone 5s (9.2)' -t <template>
But if I use node and try to use spawn like this:
var args = ['instruments', '-w', `iPhone 5s (9.2)`, '-t', 'noTemp'];
var xcrun = spawn('xcrun', args);
So it got me thinking that maybe it had some limitation opening apps? I tried to run:
var args = ['/Applications/Spotify.app'];
var xcrun = spawn('open', args);
And nothing happens. I couldn't find anything related to that. My question is: is there anyway to open apps using node.js spawn? If there is, does someone know what's the problem with my code?
Here's the full code if needed:
var args = ['instruments', '-w', `${fullDevice}`, '-t', 'noTemp'];
var xcrun = spawn('xcrun', args);
xcrun.stdout.on('data', (data)=>{
console.log(data.toString('utf8'));
})
xcrun.on('close', (code) => {
socket.emit({
time: commands.getCurrentTime(),
type: 'success',
log: 'Device booted...'
});
callback();
if (code !== 0) {
console.log(`open process exited with code ${code}`);
}
});
OBS: if I run this piece of code the application doesn't terminate, the program doesn't continue and nothing happens.
EDIT: Changed:
xcrun.on('data', (data)=>{
To:
xcrun.stdout.on('data', (data)=>{
Spawned processes have two separate streams for stdout and stderr, so you will need to listen for data on those objects and not the spawned process object itself:
xcrun.stdout.on('data', function(data) {
console.log('stdout: ' + data.toString());
});
xcrun.stderr.on('data', function(data) {
console.log('stderr: ' + data.toString());
});
The problem was one line above. Not sure why, but there's a socket.emit call that is wrong and actually hold the program's execution.

Get terminals PID out of Node.js APP [duplicate]

How to get the process name with a PID (Process ID) in Node.JS program, platform include Mac, Windows, Linux.
Does it has some node modules to do it?
Yes, built-in/core modules process does this:
So, just say var process = require('process'); Then
To get PID (Process ID):
if (process.pid) {
console.log('This process is your pid ' + process.pid);
}
To get Platform information:
console.log('This platform is ' + process.platform);
Note: You can only get to know the PID of child process or parent process.
Updated as per your requirements. (Tested On WINDOWS)
var exec = require('child_process').exec;
var yourPID = '1444';
exec('tasklist', function(err, stdout, stderr) {
var lines = stdout.toString().split('\n');
var results = new Array();
lines.forEach(function(line) {
var parts = line.split('=');
parts.forEach(function(items){
if(items.toString().indexOf(yourPID) > -1){
console.log(items.toString().substring(0, items.toString().indexOf(yourPID)));
}
})
});
});
On Linux you can try something like:
var spawn = require('child_process').spawn,
cmdd = spawn('your_command'); //something like: 'man ps'
cmdd.stdout.on('data', function (data) {
console.log('' + data);
});
cmdd.stderr.setEncoding('utf8');
cmdd.stderr.on('data', function (data) {
if (/^execvp\(\)/.test(data)) {
console.log('Failed to start child process.');
}
});
On Ubuntu Linux, I tried
var process = require('process'); but it gave error.
I tried without importing any process module it worked
console.log('This process is your pid ' + process.pid);
One more thing I noticed we can define name for the process using
process.title = 'node-chat'
To check the nodejs process in bash shell using following command
ps -aux | grep node-chat
cf official documentation https://nodejs.org/dist/latest-v10.x/docs/api/process.html#process_process_pid
the require is no more needed.
The good sample is :
console.log(`This process is pid ${process.pid}`);

Running Java keytool command from node on Windows

I'm trying to automate the creation on a keystore using Java. I'm running the child_process spawn function. For one thing, the keytool command response through the stderr channel which is odd, but it prompts me for the password. I'm unsure how to submit anything. If I call stdin.end() it kills the process.
var KEYTOOL_COMMAND = "C:\\Program Files\\Java\\jdk1.8.0_05\\bin\\keytool";
var ktArgs = ["-genkey", "-v", "-keystore", "test.keystore", "-alias", "test", "-keyalg", "RSA", "-keysize" ,"2048", "-validity", "10000"];
var spawn = require("child_process").spawn;
var cmd = spawn(KEYTOOL_COMMAND, ktArgs);
cmd.stdout.on('data', function (data) {
console.log('stdout: ' + data);
});
cmd.stderr.setEncoding('utf8');
cmd.stderr.on('data', function (data) {
cmd.stdin.write("password\\n\\r");
});
cmd.on('close', function (code) {
console.log('child process exited with code ' + code);
});
Here I'm to submit "password" as my password.
You're escaping your CR and LF, try this instead: cmd.stdin.write("password\r\n"); You might also try without the CR: cmd.stdin.write("password\n");

How to get the cwd (current working directory) from a nodejs child process (in both windows and linuxish)

I'm trying to run a script via nodejs that does:
cd ..
doSomethingThere[]
However, to do this, I need to executed multiple child processes and carry over the environment state between those processes. What i'd like to do is:
var exec = require('child_process').exec;
var child1 = exec('cd ..', function (error, stdout, stderr) {
var child2 = exec('cd ..', child1.environment, function (error, stdout, stderr) {
});
});
or at very least:
var exec = require('child_process').exec;
var child1 = exec('cd ..', function (error, stdout, stderr) {
var child2 = exec('cd ..', {cwd: child1.process.cwd()}, function (error, stdout, stderr) {
});
});
How can I do this?
to start child with parent dir as cwd:
var exec = require('child_process').exec;
var path = require('path')
var parentDir = path.resolve(process.cwd(), '..');
exec('doSomethingThere', {cwd: parentDir}, function (error, stdout, stderr) {
// if you also want to change current process working directory:
process.chdir(parentDir);
});
Update: if you want to retrieve child's cwd:
var fs = require('fs');
var os = require('os');
var exec = require('child_process').exec;
function getCWD(pid, callback) {
switch (os.type()) {
case 'Linux':
fs.readlink('/proc/' + pid + '/cwd', callback); break;
case 'Darwin':
exec('lsof -a -d cwd -p ' + pid + ' | tail -1 | awk \'{print $9}\'', callback);
break;
default:
callback('unsupported OS');
}
}
// start your child process
// note that you can't do like this, as you launch shell process
// and shell's child don't change it's cwd:
// var child1 = exec('cd .. & sleep 1 && cd .. sleep 1');
var child1 = exec('some process that changes cwd using chdir syscall');
// watch it changing cwd:
var i = setInterval(getCWD.bind(null, child1.pid, console.log), 100);
child1.on('exit', clearInterval.bind(null, i));
If you want to get the current working directory without resorting to OS specific command line utilities, you can use the "battled-tested" shelljs library that abstract these things for you, while underneath using child processes.
var sh = require("shelljs");
var cwd = sh.pwd();
There you have it, the variable cwd holds your current working directory whether you're on Linux, Windows, or freebsd.
Just a thought, if you know the child process's PID, and have pwdx installed (likely on linux), you could execute that command from node to get the child's cwd.
I think the best bet is manipulating the options.cwd between calls to exec. in exec callback this.pwd and this.cwd might give you leverage for your implementations.

Resources