- 1 year ago
Node.js run command line (child_process?)
Yes, in Node.js, you can execute command-line commands using the child_process
module. The child_process
module provides several methods to run commands and interact with the command-line environment.
Here's an example of how you can use the exec
function from the child_process
module to run a command and retrieve its output:
javascriptconst { exec } = require('child_process');
// Run a command
const command = 'ls -l'; // Replace with your desired command
exec(command, (error, stdout, stderr) => {
if (error) {
console.error(`Error executing command: ${error.message}`);
return;
}
if (stderr) {
console.error(`Command execution error: ${stderr}`);
return;
}
console.log(`Command output:\n${stdout}`);
});
In this example, the exec
function runs the specified command (ls -l
in this case) in a child process. The output of the command is captured and passed to the callback function. The stdout
parameter contains the standard output of the command, while stderr
holds the standard error output. If an error occurs during command execution, the error
parameter will contain the error information.
You can replace 'ls -l'
with any command you want to run on the command line. Make sure to handle the output and error appropriately within the callback function.
Note: The exec
function is suitable for running simple commands. If you need more advanced functionality like streaming output or handling large amounts of data, you can explore other functions provided by the child_process
module, such as spawn
or execFile
.
Remember to refer to the official Node.js documentation for more details on the child_process
module and its available methods: https://nodejs.org/api/child_process.html