node.js shell command execution
There are three issues here that need to be fixed:
First is that you are expecting synchronous behavior while using stdout asynchronously. All of the calls in your run_cmd
function are asynchronous, so it will spawn the child process and return immediately regardless of whether some, all, or none of the data has been read off of stdout. As such, when you run
console.log(foo.stdout);
you get whatever happens to be stored in foo.stdout at the moment, and there's no guarantee what that will be because your child process might still be running.
Second is that stdout is a readable stream, so 1) the data event can be called multiple times, and 2) the callback is given a buffer, not a string. Easy to remedy; just change
foo = new run_cmd(
'netstat.exe', ['-an'], function (me, data){me.stdout=data;}
);
into
foo = new run_cmd(
'netstat.exe', ['-an'], function (me, buffer){me.stdout+=buffer.toString();}
);
so that we convert our buffer into a string and append that string to our stdout variable.
Third is that you can only know you've received all output when you get the 'end' event, which means we need another listener and callback:
function run_cmd(cmd, args, cb, end) {
// ...
child.stdout.on('end', end);
}
So, your final result is this:
function run_cmd(cmd, args, cb, end) {
var spawn = require('child_process').spawn,
child = spawn(cmd, args),
me = this;
child.stdout.on('data', function (buffer) { cb(me, buffer) });
child.stdout.on('end', end);
}
// Run C:\Windows\System32\netstat.exe -an
var foo = new run_cmd(
'netstat.exe', ['-an'],
function (me, buffer) { me.stdout += buffer.toString() },
function () { console.log(foo.stdout) }
);
Executing shell command using child process
If you take a look at the child process docs, they say exec
:
spawns a shell and runs a command within that shell, passing the stdout and stderr to a callback function when complete.
However, Ganache is a process that continues running and doesn't "complete" until you kill it. This allows you to send multiple requests to Ganache without it shutting down on you.
How to run shell script file using nodejs?
You can execute any shell command using the shelljs module
const shell = require('shelljs')
shell.exec('./path_to_your_file')
Execute and get the output of a shell command in node.js
This is the method I'm using in a project I am currently working on.
var exec = require('child_process').exec;
function execute(command, callback){
exec(command, function(error, stdout, stderr){ callback(stdout); });
};
Example of retrieving a git user:
module.exports.getGitUser = function(callback){
execute("git config --global user.name", function(name){
execute("git config --global user.email", function(email){
callback({ name: name.replace("\n", ""), email: email.replace("\n", "") });
});
});
};
Electron and NodeJS: Execute shell command asyncronously with live stream
You need to use ffmpeg with ffmpeg-progress-wrapper. Attach on event "progress" and get the "progress" property.
process.on('progress', (progress) => console.log(JSON.stringify(progress.progress));
It goes from 0 to 1, so you will need to set some adjusts.
Execute shell commands using nodejs with root access
You can combine all 4 commands into one by Ref: Super User answer
echo "<password>" | sudo -S "<command that needs a root access>"
In your NodeJs code - try one of the following:
- Pure JS way
var command='echo "<password>" | sudo -S "<command that needs a root access>"';
child_process.execSync(command)
- Using Library shell-exec - helper library which uses child_process.spawn
const shellExec = require('shell-exec')
var command='echo "<password>" | sudo -S "<command that needs a root access>"';
shellExec('echo Hi!').then(console.log).catch(console.log)
Be sure to validate the command that need to be executed, before triggering execute to avoid unwanted results.
Related Topics
How to Put an Image File in a JSON Object
Dynamically Arrange Some Elements Around a Circle
How to Remove the Decimal Part from JavaScript Number
How to Define Setter/Getter on Prototype
JavaScript Use Variable as Object Name
How to Check Whether <Ng-Content> Is Empty? (In Angular 2+ Till Now)
How Do Pipes and Monads Work Together in JavaScript
Get Wrong Value in Data Attribute Jquery
Fix Node Position in D3 Force Directed Layout
Fulfill (Don't Resolve) Promise with Another Promise
How to Rotate a 3D Object on Axis Three.Js
How to Check If a Number Is Between Two Values
How to Close a Dropdown on Click Outside
Differencebetween Parseint(String) and Number(String) in JavaScript