In Node.js, you can use the child_process module to run shell scripts at startup. Here's a simple example demonstrating how to execute a shell script when your Node.js application launches:
Assume your shell script is named script.sh and located in the project's root directory.
Ensure the script has executable permissions:
shchmod +x script.sh
Then, in your Node.js code, you can use the exec method from the child_process module to run it:
javascriptconst { exec } = require('child_process'); // This function executes the shell script function runShellScript() { exec('./script.sh', (error, stdout, stderr) => { if (error) { console.error(`Error executing: ${error}`); return; } if (stderr) { console.error(`Shell script error output: ${stderr}`); return; } console.log(`Shell script output: ${stdout}`); }); } // Execute at application startup runShellScript(); // ... rest of your Node.js application code ...
In the above code, the exec function is used to execute external commands. Its parameters include the command string to run and a callback function. This callback is invoked after script execution completes, regardless of success or failure, providing error, stdout, and stderr parameters.
Ensure security when performing these steps: only execute trusted scripts to prevent potential security risks.
Additionally, if your script is asynchronous or you need to perform actions based on the script's output after execution, ensure your Node.js application properly handles asynchronous operations. In the above example, Node.js continues running after the callback executes, but sometimes you may need to wait for the script to complete before proceeding with other tasks. In such cases, use the async/await pattern and the promisify utility to manage asynchronous calls.