Home >Web Front-end >JS Tutorial >How to Execute Shell Commands Using JavaScript\'s \'exec\' Function?
Executing Shell Commands Seamlessly in JavaScript
JavaScript's versatility extends beyond web development to include powerful capabilities for system interaction. One crucial aspect of this is the ability to execute shell commands and retrieve their outputs.
How to Execute Shell Commands in JavaScript
To execute shell commands in JavaScript, we leverage the child_process module provided by Node.js. This module offers a range of methods for working with external processes, including the exec function.
Example Code
The following code demonstrates how to execute the cat command with a pipe and the wc command using exec:
<code class="javascript">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); } });</code>
Breaking Down the Code
The callback function receives three arguments:
Note:
This code assumes you are using Node.js as your JavaScript runtime. You may need to adjust the syntax or import statements if you are using a different JavaScript framework or environment.
The above is the detailed content of How to Execute Shell Commands Using JavaScript\'s \'exec\' Function?. For more information, please follow other related articles on the PHP Chinese website!