Executing a shell command
Published on: 27th May 2025
Overview
In order to automate the system installation process, we have to create some sort of "script" file to do the job. In the Linux world, most of the automation script is written in Bash or Python.
Today, we are going to use Node.js to do this job since our systems are written in JavaScript. One of the advantages of writing Node.js script is that it will be able to access the libraries that we have developed. It is helpful and allows us to complete the installation script in a shorter time.
To write the installation script in Node.js, we have to use execSync
, a built-in function in child_process
package. Basically, the execSync
is executing the command within a shell and this is the key difference if you compare it to the spawnSync
function.
Some use cases
Here's the two commonly use cases in any installation script.
Patching the directory permission
Let's say our systems will be kept in '/var/my-app-directory' and this directory is accessible to 'user1' and 'group1' (the user group). The next important action is to ensure that all files inside this directory do not have execute permission.
const { execSync } = require('child_process');
let update_dir = '/var/my-app-directory';
execSync(`chown user1:group1 ${update_dir} -R`);
execSync(`find ${update_dir} -type d -exec chmod 775 {} \\;`);
execSync(`find ${update_dir} -type f -exec chmod 664 {} \\;`);
Decompressing 7z file
Once the app has been downloaded to the '/var' directory, we will decompress using the 7z
program. For your information, we need the password feature provided by 7z
. The following example is the simplest way to extract a 7z file and it is for illustration purposes.
const { execSync } = require('child_process');
let my_app_7z = '/var/my-app.7z';
execSync(`7z x {my_app_7z}`);
Other things that you can achieve with executing shell command
- Download the installer with
fetch()
function just likecurl
orwget
command but in JavaScript flavor. - Creating certificates with
crypt.generateKeyPairSync()
function. Our system needs the certificate for encrypting important information. Each installation will have to create its own certificates in order to minimize the attack if one of the installations has been compromised. - Initializing the database structure by running the SQL script files. Because you have already downloaded and decompressed your system codes, you will be able to run your database scripts with ease by calling your database JavaScript file.
Conclusion
Executing a shell command is quite straightforward. But, you still have to learn the basic shell commands especially on the security permission command like chown
or chmod
.
Back to #NODEJS blog
Back to #blog listing
Author
Lau Hon Wan, software developer.