This code imports the exec
function, which enables Node.js to execute shell commands and interact with the spawned processes.
npm run import -- "Start the selenium server and crawl 16 search results at once"
var exec = require('child_process').exec;
/**
* Child Process Wrapper
* @module childProcessWrapper
*/
const childProcess = require('child_process');
/**
* Execute a shell command and get the result
* @param {string} command - The command to execute
* @param {string} [encoding='utf8'] - Encoding to use for the result
* @param {function} callback - Callback function to handle the result
*/
function executeCommand(command, encoding = 'utf8', callback) {
childProcess.exec(command, (error, stdout, stderr) => {
if (error) {
console.error(`Command failed: ${error.message}`);
return callback(error);
}
console.log(`Command output: ${stdout}`);
callback(null, stdout);
});
}
/**
* Execute a shell command and return a promise
* @param {string} command - The command to execute
* @return {Promise} - A promise that resolves with the command output
*/
function executeCommandPromise(command) {
return new Promise((resolve, reject) => {
childProcess.exec(command, (error, stdout, stderr) => {
if (error) {
console.error(`Command failed: ${error.message}`);
reject(error);
} else {
resolve(stdout);
}
});
});
}
// Example usage:
executeCommandPromise('echo "Hello, World!"').then((result) => {
console.log(`Result: ${result}`);
});
This code snippet imports the exec
function from Node.js's child_process
module.
Here's a breakdown:
require('child_process')
: This line imports the child_process
module, which provides utilities for interacting with child processes.
.exec
: This selects the exec
function from the imported child_process
module.
Purpose:
The exec
function allows you to execute shell commands from within your Node.js code. It takes a command string as input and returns a ChildProcess
object representing the spawned process. This object provides methods for interacting with the child process, such as reading its output and handling its exit code.