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

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.

Related

How can I handle an input prompt with node when executing a command via child_process?

For context, I'm on a Mac and I'm trying to script a 1Password CLI signin via their command-line tool. I'm trying to programmatically signing using a command that looks like:
op signin <signinaddress> <emailaddress> <secretkey> --output=raw
and I've tried with/without the --output=raw argument, but every time I simply get an error that looks like
[LOG] 2019/06/04 00:57:45 (ERROR) operation not supported on socket
child process exited with code 1
My initial hunch was that it had something to do with the command executions prompt displaying this special key character in the following image:
The relevant code is written in TypeScript and looks like this:
import { spawn } from 'child_process'
// ends up being `op signin <signinaddress> <emailaddress> <secretkey>`
const op = spawn(opExecutable, args);
let result: string | null = null
op.on('message', (message, sendHandle) => {
console.log('message', message, sendHandle)
});
op.stdout.on('data', (data) => {
console.log(`stdout: ${data}`);
if (data && typeof data.toString === 'function') {
result = data.toString()
}
});
op.on('close', (code, ...args) => {
console.log(`child process exited with code ${code}`, args);
});
Eventually, I'd like to run on all platforms and be able pass in stdin for the master password required to sign in, but I'm trying to figure out why my node app is crashing first :)
Apparently I was pretty close to a solution by using spawn, but I needed to specify configuration for stdio. Here's an example snippet of how I used spawn that worked for me:
const proc = spawn(
cmd, // the command you want to run, in my case `op`
args, // arguments you want to use with the above cmd `signin`, etc.
{
stdio: [
'inherit', // stdin: changed from the default `pipe`
'pipe', // stdout
'inherit' // stderr: changed from the default `pipe`
]
});

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}`);

Redirecting output to a log file using node.js

I have a child process that I am using as follows in node.js. Instead of redirecting the output to the console I would like to put the output in a log file located somewhere on the machine this is running on (and should work for both windows and mac).
The code below is what I am using and I would like to output the files into a log file. What changes needed to do that here? Thanks!
My Code:
var spawn = require('child_process').spawn,
ls = spawn('ls', ['-lh', '/usr']);
ls.stdout.on('data', function (data) {
console.log('stdout: ' + data);
});
ls.stderr.on('data', function (data) {
console.log('stderr: ' + data);
});
ls.on('close', function (code) {
console.log('child process exited with code ' + code);
});
Here's an example of logging to file using streams.
var logStream = fs.createWriteStream('./logFile.log', {flags: 'a'});
var spawn = require('child_process').spawn,
ls = spawn('ls', ['-lh', '/usr']);
ls.stdout.pipe(logStream);
ls.stderr.pipe(logStream);
ls.on('close', function (code) {
console.log('child process exited with code ' + code);
});
There are two ways you can achieve this, one is using
let logConsoleStream = fs.createWriteStream('./logConsoleFile.log', {flags: 'a'});
let logErrorStream = fs.createWriteStream('./logErrorFile.log', {flags: 'a'});
and redirect all logs or errors using this
ls.stdout.pipe(logConsoleStream ); // redirect stdout/logs only
ls.stderr.pipe(logErrorStream ); // redirect error logs only
by separating log files you will have separate files for Error logs and console logs
this is exactly same as generalhenry shared above
And Second Way for Achieving this with the help of Command Line
when you execute node app from the command line
node app/src/index.js
you can specify here where you want to redirect logs and Errors from this application
there are three stream redirection commands using the command line
`>` It will redirect your only stdout or logs to the specified path
`2>` It will redirect your errors logs to the specified path
`2>&1 ` It will redirect all your stdout and stderr to a single file
example: how you will use these commands
node app/src/index.js > ./logsOnly.txt
node app/src/index.js 2> ./ErrorsOnly.txt
node app/src/index.js 2>&1 ./consoleLogsAndErrors.txt
I hope someone coming later finds this helpful
if there is I done wrong way please do let me know it will help me and others
Thanks
If you run your JS script with forever then you have the option to define a log file as parameter which will handle all your console.log messages. Not to mention the benefit of keeping your nodejs app live permanently.
Alternatively try this:
sudo forever start myapp.js 2>&1 /home/someuser/myapp/myapp.log
use forever with below options
forever start -o out.log -e err.log server.js
The best answer was in the comments and is mentioned in a previous question here: stackoverflow.com/questions/2496710/nodejs-write-to-file
It is as follows:
var fs = require('fs');
fs.writeFile("/tmp/test", "Hey there!", function(err) {
if(err) {
console.log(err);
} else {
console.log("The file was saved!");
}
});

NODEJS process info

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}`);

Resources