How to execute shell command in javascript

I want to write a JavaScript function that will execute system shell commands (e.g. ls ) and return a value.

How do I achieve this?

+87
javascript
Dec 10 '09 at 10:54
source share
15 answers

What if the client that this javascript is running on is running Windows? This means that what you are trying to achieve is impossible. Javascript is a scripting language for clients and runs in an isolated environment, often found in a web browser, which prevents access to resources on the computer.

-90
Dec 10 '09 at 10:56
source share
โ€” -

Many other answers here seem to solve this problem in terms of the JavaScript function executed in the browser. I will shoot and answer, assuming that when the asker said "Shell script", he meant the JavaScript backend Node.js. Maybe use commander.js to use the frame of your code :)

You can use the child_process module from the node API. I inserted the sample code below.

 var exec = require('child_process').exec, child; child = exec('cat *.js bad_file | wc -l', function (error, stdout, stderr) { console.log('stdout: ' + stdout); console.log('stderr: ' + stderr); if (error !== null) { console.log('exec error: ' + error); } }); child(); 

Hope this helps!

+110
Dec 17 '13 at 15:33
source share

... after few years...

ES6 has been adopted as standard , and ES7 is around the corner, so it deserves an updated answer. As an example, we will use ES6 + async / await with nodejs + babel, the necessary conditions are:

An example of your foo.js file might look like this:

 import { exec } from 'child_process'; /** * Execute simple shell command (async wrapper). * @param {String} cmd * @return {Object} { stdout: String, stderr: String } */ async function sh(cmd) { return new Promise(function (resolve, reject) { exec(cmd, (err, stdout, stderr) => { if (err) { reject(err); } else { resolve({ stdout, stderr }); } }); }); } async function main() { let { stdout } = await sh('ls'); for (let line of stdout.split('\n')) { console.log(`ls: ${line}`); } } main(); 

Make sure you have babel:

 npm i babel-cli -g 

Install the latest preset:

 npm i babel-preset-latest 

Run it through:

 babel-node --presets latest foo.js 
+35
Aug 08 '15 at 19:48
source share

It depends entirely on the JavaScript environment. Please specify.

For example, in Windows Scripting you do things like:

 var shell = WScript.CreateObject("WScript.Shell"); shell.Run("command here"); 
+16
Dec 10 '09 at 10:58
source share

In a nutshell:

 // Instantiate the Shell object and invoke its execute method. var oShell = new ActiveXObject("Shell.Application"); var commandtoRun = "C:\\Winnt\\Notepad.exe"; if (inputparms != "") { var commandParms = document.Form1.filename.value; } // Invoke the execute method. oShell.ShellExecute(commandtoRun, commandParms, "", "open", "1"); 
+14
Dec 10 '09 at 10:58
source share

I do not know why the previous answers gave all sorts of complicated solutions. If you just want to execute a quick command like ls , you don't need async / await or callbacks or anything else. Here all you need is execSync :

 const execSync = require('child_process').execSync; // import { execSync } from 'child_process'; // replace ^ if using ES modules const output = execSync('ls', { encoding: 'utf-8' }); // the default is 'buffer' console.log('Output was:\n', output); 

To handle errors, add a try / catch around the statement.

If you are executing a command that takes a lot of time, then yes, look at the asynchronous function exec .

+11
Sep 30 '18 at 6:06
source share

With NodeJS, it's easy! And if you want to run this script every time you load your server, you can watch the forever-service application!

 var exec = require('child_process').exec; exec('php main.php', function (error, stdOut, stdErr) { // do what you want! }); 
+7
Dec 07 '16 at 2:31
source share

Note. These responses are from a browser-based client to a Unix-based web server.

Run the command on the client

You essentially cannot. Security only works in the browser, and access to commands and the file system is limited.

Run ls on the server

You can use the AJAX call to get a dynamic page passing your parameters via GET.

Keep in mind that this also poses a security risk, as you will need to do something to ensure that the attacker mrs rouge does not get your application to run: / dev / null && & & rm -rf / .... ..

So, in nutshel, starting from JS is just a bad, bad idea .... YMMV

+5
Dec 10 '09 at 11:03
source share

Another post on this subject with a good jQuery / Ajax / PHP solution:

shell scripting and jQuery

+3
05 Apr '12 at 18:37
source share

In IE, you can do this:

 var shell = new ActiveXObject("WScript.Shell"); shell.run("cmd /c dir & pause"); 
+2
Mar 21 '14 at 7:18
source share

Here is a simple command that executes the Linux shell ifconfig command

 var process = require('child_process'); process.exec('ifconfig',function (err,stdout,stderr) { if (err) { console.log("\n"+stderr); } else { console.log(stdout); } }); 
+1
Sep 16 '15 at 8:06
source share

With nashorn, you can write a script as follows:

 $EXEC('find -type f'); var files = $OUT.split('\n'); files.forEach(... ... 

and run it:

 jjs -scripting each_file.js 
+1
Dec 06 '16 at 19:37
source share
 function exec(cmd, handler = function(error, stdout, stderr){console.log(stdout);if(error !== null){console.log(stderr)}}) { const childfork = require('child_process'); return childfork.exec(cmd, handler); } 
0
Apr 27 '19 at 17:25
source share

In java, depending on privileges:

 Runtime run = Runtime.getRuntime(); Process pr = run.exec("ls"); pr.waitFor(); BufferedReader buf = new BufferedReader(new InputStreamReader(pr.getInputStream())); String line = ""; while ((line=buf.readLine())!=null) { System.out.println(line); } 

In JavaScript, you cannot. They are really two completely different things.

EDIT

My answer was written when the question had java and javascript tags. Since the OP doesn't seem to make a distinction, I don't think I can say exactly what is being requested here.

-one
Dec 10 '09 at 10:55
source share

using these steps, you can succeed,

  1. vim command.js
  2. copy n past this

#!/usr/bin/env node

 function execute(command) { const exec = require('child_process').exec exec(command, (err, stdout, stderr) => { process.stdout.write(stdout) }) } execute('echo "Hello World!"') 
  1. node command.js
-one
Sep 20 '18 at 19:45
source share



All Articles