This guide will demonstrate how to execute shell commands within JavaScript using the child_process module provided by Node's API.
To achieve this in JavaScript, you will use the exec function from the child_process module. This function allows you to execute shell commands from within your JavaScript code and access their output.
var exec = require('child_process').exec; 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); } } );
In the example above, the exec function is invoked with the shell command cat *.js bad_file | wc -l. This command will execute the cat command to concatenate the contents of all .js files and the non-existent file bad_file. It then pipes the output to the wc -l command, which counts the number of lines in the output.
The exec function takes three additional parameters:
The above is the detailed content of How to Execute Shell Commands in JavaScript Using the \'exec\' Function?. For more information, please follow other related articles on the PHP Chinese website!