How to handle mysql command-line password prompt using exec function - node.js

I don't know how id pipe the password variable in the exec function.
I've tried running it, but no prompt appears.
const {user,password,database} = require('./config.js');
const { exec } = require('child_process');
const comm = `mysql -u ${user} -p ${database} < ${QUERY_PATH} `
exec(comm)

I guess the only part missing is to use the callback, as recommended by Node in https://nodejs.org/api/child_process.html#child_process_child_process_exec_command_options_callback .
Replace:
exec(comm)
by:
exec(comm, (error, stdout, stderr) => {
console.log(stdout);
})
This way, you need to type the password manually. If you don't want to type the password manually (not recommended, mySQL warns about safety concerns using this second method), then the code would be:
const comm = `mysql -u${user} -p${password} ${database} < ${QUERY_PATH}`
If you want to check what is the error happening to you, and that's how I debugged, use the callback function to log the errors:
exec(comm, (error, stdout, stderr) => {
if (error) {
console.error(`exec error: ${error}`);
return;
}
console.log(`stdout: ${stdout}`);
console.error(`stderr: ${stderr}`);
});

Related

How to run function in child process in Node.js

I've been able to successfully run commands using the exec() command. However, I'd like to leave a process running and continue to run commands on the open process, then close on app exit. Take this generic code:
const { exec } = require("child_process");
exec("XR_Command -i 192.168.0.100 -f /ch/01/on | kill", (error, stdout, stderr) => {
if (error) {
console.log(`error: ${error.message}`);
return;
}
if (stderr) {
console.log(`stderr: ${stderr}`);
return;
}
console.log(`stdout: ${stdout}`);
});
I would like to keep the XR_Command process active so that I can issue commands to the active process. So, basically I would like to do this:
> XR_Command -i 192.168.0.100
> /ch/01/on
> /ch/02/on
> /ch/03/on
I cannot for the life of me figure out how to make this function properly by referencing the existing child process. Thanks!
Okay, so after a day I figured out two main problems I was running in to, here is my working code:
const { spawn } = require('child_process');
let Command = spawn('X_Control', ['-i', '192.168.0.1']);
Command.stdout.pipe(process.stdout);
Command.stderr.pipe(process.stderr);
Command.stdin.write('some command\n');
Command.on('error', function(err) {
console.error(err);
});
Command.stderr.on('data', (data) => {
console.log(`stderr: ${data}`);
});
Command.on('close', (code) => {
console.log(`child process exited with code ${code}`);
});
Issue 1: My application command was X_Control -i 192.168.0.1, every space needs to be quoted separately as Command = spawn('X_Control', ['-i', '192.168.0.1']); This took me a while to track down.
Issue 2: Command.stdin.write('some command\n'); is how I execute commands on my running application, and it must be followed by \n in order to execute the command.

Node.js child processes to run python code not responding

I have an Express Node.js application, but I want to run python code (send data and receive results)
but when I'm testing it using postman still loading and I don't have any response.
my node.js code
router.get('/name', callName);
function callName(req, res) {
var exec = require("child_process").exec;
var process = exec('python',["./hello.py",
req.query.firstname,
req.query.lastname
] );
process.stdout.on('data', function(error,data) {
console.log('stderr: ', error);
res.send(data.toString());
} )
}
python code
import sys
# Takes first name and last name via command
# line arguments and then display them
print("Output from Python")
print("First name: " + sys.argv[1])
print("Last name: " + sys.argv[2])
# Save the script as hello.py
thank you #nijm I found the solution
first The child_process.exec method doesn't accept the command arguments as an array (like child_process.spawn does).
second,
u must have python installed on ur machine.
third
u must have python file in a public folder (in my case uploads folder)
all these steps don't mention in any tutorial or an example about How to call a Python function from Node.js
at the end of the day, my code is
router.get('/name', callName);
function callName(req, res) {
var exec = require("child_process").exec;
exec(`python uploads/hello.py ${req.query.firstname} ${req.query.lastname}`, (error, stdout, stderr) => {
if (error) {
console.error(`exec error: ${error}`);
return;
}
console.log(`stdout: ${stdout}`);
console.log(`stderr: ${stderr}`);
});
}
python code
import sys
# Takes first name and last name via command
# line arguments and then display them
print("Output from Python")
print("First name: " + sys.argv[1])
print("Last name: " + sys.argv[2])
# Save the script as hello.py
The child_process.exec method doesn't accept the command arguments as an array (like child_process.spawn does), try this (untested):
var exec = require("child_process").exec;
exec(`python ./hello.py ${req.query.firstname} ${req.query.lastname}`, (error, stdout, stderr) => {
if (error) {
console.error(`exec error: ${error}`);
return;
}
console.log(`stdout: ${stdout}`);
console.log(`stderr: ${stderr}`);
});

Run Bash-Script within Electron App using child_process.exec

I'm struggling with running a bash-script within main.html.
const exec = require("child_process").exec;
// Execute bash script
exec("/c/workspace/_edu_zone/Proxy_Manager/filemover.sh", shellCallback);
// Callback
function shellCallback(error, stdout, stderr) {
console.log(error, stdout)
}
I'm always getting the error: no such file or directory. What am i doing wrong?
Any help is highly appreciated.
change
/c/workspace/_edu_zone/Proxy_Manager/filemover.sh
to
c:/workspace/_edu_zone/Proxy_Manager/filemover.sh
or
your could try using node-powershell to execute the command directly
const shell = require('node-powershell')
let ps = new shell({
executionPolicy: 'Bypass',
noProfile: true
});
function lunchnode() {
process.stdout.write('logging');
ps.addCommand('node run.js')
ps.invoke()
.then(function (output) {
process.stdout.write(output)
}).catch(function (err) {
process.stdout.write(err)
ps.dispose()
})
}

How to make normal function to be returning in node.js

function puts(error, stdout, stderr) {
if (error) {
console.log("error", "Error connecting");
result = "Failed";
console.log(result)
}
else {
sys.puts(stdout)
result = "Success"
console.log(result)
}
}
//The calling function is mentioned as below:
app.get('/api/platforms1', function(req, res){
exec("ping localhost",puts);
});
//I am working under mean stack.I have created a method to ping ip address and display their result.But now I want to display the result as a return function.How can we do it??
First:
In windows, if you use:
ping google.com
You will get only 4 information ping, but on Ubuntu, if you use that command, the ping can't stop until you stop it with Ctrl+C.
To fix this we need to use -c flag. The -c option tells ping program to stop after sending (or receiving) specified number of ECHO_RESPONSE packets.
Second:
you need to use res.send to send back the ping response but due to your callback function i.e puts you don't have the access for res and req.
Use this wrapper func to pass another arguments you want to access with your callback
function execute(command, callback, res) {
exec(command, function(error, stdout, stderr) {
// Notice extra params I have passed here^, ^
callback(error, stdout, stderr, res);
});
}
and you can use this as
execute("ping -c 2 google.com", puts, /*pass extra params*/ res);
and catch extra params here after your callback function
||
---------- \/
function execute(command, callback, res) {
...
}
Complete code:
var exec = require('child_process').exec;
function puts(error, stdout, stderr, res) {
// Notice extra params here ^
if (error) {
console.log("error", "Error connecting");
result = "Failed";
console.log(result)
} else {
sys.puts(stdout)
result = "Success"
console.log(result)
//send response to client
res.send(result)
}
}
//The calling function is mentioned as below:
app.get('/api/platforms1', function(req, res) {
execute("ping -c 1 google.com", puts, /*pass extra params*/ res);
});
function execute(command, callback, res) {
exec(command, function(error, stdout, stderr) {
// Notice extra params I have passed here^, ^
callback(error, stdout, stderr, res);
});
}
Ref:
https://askubuntu.com/questions/200989/ping-for-4-times
Get the output of a shell command in node.js
First of all sys is deprecated you can use util instead of it.
And if you want to get your result wherever, that thing you can do with callback, since Node.js nature is asynchronous.

(Node.js) How to store stdout.pipe into a variable?

I want to get free -m (linux shell command) and store its result into a variable
by using source code below:
var spawn = require('child_process').spawn,
command = spawn('free', ['-m']);
command.stdout.pipe(process.stdout);
Is there any way to store process.stdout in a variable, please me some suggestions
This is fairly simple with child_process.exec:
var child = require("child_process");
var freeOut;
child.exec("free", ["-m"], function (error, stdout, stderr) {
if (error) {
console.error(error, stderr);
return;
}
//stdout and stderr are available here
freeOut = stdout;
process.stdout.write(stdout);
});
//Note. Do NOT use freeOut here. exec is async. Can only use in the callback

Resources