How to run bash commands from Node.js and get result - javascript

I want to run a bash script on my server using a Node js function and get the result back in Node through a callback. Sample script is as follows -
grep -c "eventName" 111data.csv
Is this possible? I looked at the following module but looks very complex. Does anyone know of a way this can be done?
https://www.npmjs.com/package/bashjs

You can execute a command
const { exec } = require('child_process');
const grep = exec('grep -c "eventName" 111data.csv', function (error, stdout, stderr) {
if (error) {
console.log(error.stack);
console.log('Error code: '+error.code);
console.log('Signal received: '+error.signal);
}
console.log('Child Process STDOUT: '+stdout);
console.log('Child Process STDERR: '+stderr);
});
grep.on('exit', function (code) {
console.log('Child process exited with exit code '+code);
});
Just modified the example from the Node.js article. Didn't actually test it

Related

How can I run command which has it own options in node child process exec

I am creating make node CLI automate my npm package publishing, I am struck by this problem. After all Confirmation, I want to run the command semantic-release but problem it has its own prompts
I currently use exec command but It does not show any prompts created by semantic-release
Code
const timer = showLoading(`running ${chalk.blue(command)} `);
exec(command, (error, stdout, stderr) => {
process.stdout.write(chalk.dim(`\r running ${chalk.blue(command)} `));
clearInterval(timer);
defaults.onFinish();
if (error) {
defaults.onError(error);
console.log(error);
}
defaults.onSuccess(stdout);
console.log(stdout);
});
You can show the prompts by spawning a synchronous child process that inherits it's stdio pipes from the parent process.
JS :
import { spawnSync } from 'child_process';
let { status } = spawnSync('./test.sh', [], { stdio: 'inherit' });
if (status > 0) { throw new Error('spawned process exited abnormally'); }
test.sh
#!/bin/bash
read -p 'enter something: ' value
[ -z "$value" ] && exit 1
echo "$value"
I have used this way to create my own CLI, it's an easy way to create all the commands that I want and to do what I want, check the link maybe that helps you, in the website there also good explanation with images
Click here

Capturing exit code from python in JS via cmd child process

So I have python script called main.py
#!/usr/bin/env python3
print("hello")
exit (12)
I am trying to capture the exit code via nodejs
const cp = require('child_process');
cp.exec('python main.py', (er, stdout, stderr) => {
console.log(stdout)
}).on('close', (code) => {
console.log(code)
});
This works and outputs "hello" and "12". But I need to execute python script via another cmd unit. I have tried the code below
const cp = require('child_process');
cp.exec('start cmd /k python ./main.py', (er, stdout, stderr) => {
console.log(stdout)
}).on('close', (code) => {
console.log(code)
});
But this outputs "hello" and "0" instead of "12". I have been trying to figure this out for past couple hours but not getting anywhere. What am I missing here?
Calling a another child process is not solution for me, since I am also trying to run the python script on a development unit instead on cmd

I am trying to execute a file in sh with nodejs but the console tells me that the file cannot be found

This is the code that i found on the internet:
const { exec } = require('child_process');
var yourscript = exec('sh launch.sh', (error, stdout, stderr) => {
console.log(stdout);
console.log(stderr);
if (error !== null) {
console.log(`exec error: ${error}`);
}
});
and here is my sh file which is in the same file as my previous code:
echo "Hi There!"
but each time I run the program the console shows me:
exec error: Error: Command failed: sh launch.sh
sh: 0: Can't open launch.sh
Can somebody help me with my code please?
First, you seem to have a file permissions issue, so to fix that, start by setting the file permissions for the user as the user needs execution permissions:
chmod 755 launch.sh
Second, the code you found online is using "exec" that is now deprecated in favour of builtin child_process.execFile. So, for your needs the code would look a bit like:
var child_process = require('child_process');
child_process.exec('sh launch.sh', function(error, stdout, stderr){
console.log(stdout);
});
This should help to get started! The inner command sh launch.sh should be executable in the command line, directly, so tested without running the main host or nodejs script! Type the command in your CLI and press enter! Alternatively to calling sh launch.sh do /bin/sh launch.sh
Of course, you might want to look at docs to improve the implementation and fully understand file permissions under your OS, what sh means and finally child_process.exec.
https://www.linux.com/tutorials/understanding-linux-file-permissions
https://en.wikipedia.org/wiki/Bourne_shell
https://nodejs.org/api/child_process.html

how to execute js script file as child process node.js

I have a problem, I'm trying to execute file that sending mail using nodemailer and I need to execute it from another JS file I tried to do it like this:
const exec = require('child_process').exec;
exec('"C:/Users/NikitaSeliverstov/node_modules/.bin/send.js"');
but mail is not sending. I don't need to send params the file send.js just sending text file with fully specified path . Sorry for obvious question but I can't figure it out.
Also I tried to do it like this:
const exec = require('child_process').exec;
exec('"node C:/Users/NikitaSeliverstov/node_modules/.bin/send.js"');
you need to specify a callback function which will be called after your exec command is executed:
i created 2 files:
anotherTest.js
console.log('another test');
test.js
const exec = require('child_process').exec;
const child = exec('node anotherTest.js',
(error, stdout, stderr) => {
console.log(`stdout: ${stdout}`);
console.log(`stderr: ${stderr}`);
if (error !== null) {
console.log(`exec error: ${error}`);
}
});
this is the output:
stdout: another test
stderr:
you run the test.js script by doing "node test.js" in the terminal/console. you can change the arguments of the exec command with the arguments that you want.

How to run windows cmd.exe commands from javascript code run on node bash?

Is there a way where I can invoke a windows batch file from inside the javascript code? Or any other healthy way to do the below through any node package?
scripts.bat
ECHO "JAVASCRIPT is AWESOME"
PAUSE
scripts.js
// Code to read and run the batch file //
On the command prompt:
C:/> node scripts.js
One way to do this is with child_process. You just have to pass the file you want to execute.
const execFile = require('child_process').execFile;
const child = execFile('scripts.bat', [], (error, stdout, stderr) => {
if (error) {
throw error;
}
console.log(stdout);
});

Categories