Executing Shell Commands in JavaScript
When working with Node.js, you may encounter a need to interact with the system shell to perform tasks such as executing system commands. This article will guide you through how to achieve this using JavaScript.
Implementation
To execute a shell command in JavaScript, you can utilize the child_process module. Here's an example:
<code class="javascript">const exec = require('child_process').exec; exec('ls', (error, stdout, stderr) => { if (error) { console.log('Error executing shell command:', error); } else { console.log('Command output:', stdout); } });</code>
In this example, the ls command is executed, and its output is returned in the stdout variable. If an error occurs during the command execution, it will be accessible in the error variable.
Additional Considerations
The above is the detailed content of How to Execute Shell Commands in JavaScript Using Node.js?. For more information, please follow other related articles on the PHP Chinese website!