Comprehensive Guide to Shelljs Enhancing Your Node.js Scripts with Practical Examples

Introduction to ShellJS

ShellJS is a portable Unix shell commands for Node.js. It provides a way to execute shell commands, enabling developers to automate and manage their workflows efficiently within Node.js scripts. In this blog, we’ll dive into dozens of useful ShellJS APIs with practical code snippets to help you get started and boost your productivity.

Installing ShellJS

  
    npm install shelljs
  

Basic Usage

Include ShellJS in your project:

  
    const shell = require('shelljs');
  

API Examples

Executing Shell Commands

Execute a command and get the result:

  
    if (shell.exec('echo hello').code !== 0) {
      shell.echo('Error: Command failed');
      shell.exit(1);
    }
  

Changing Directory

Change the current working directory:

  
    shell.cd('/path/to/dir');
  

Listing Directory Contents

List files in a directory:

  
    shell.ls('/path/to/dir');
  

Copying Files

Copy files or directories:

  
    shell.cp('-R', 'source', 'destination');
  

Moving Files

Move files or directories:

  
    shell.mv('source', 'destination');
  

Removing Files

Remove files or directories:

  
    shell.rm('-rf', 'path/to/file');
  

Setting Environment Variables

Set environment variables:

  
    shell.env['VAR_NAME'] = 'value';
  

Creating Directories

Create directories:

  
    shell.mkdir('-p', 'path/to/dir');
  

Checking File Existence

Check if a file exists:

  
    if (shell.test('-e', 'path/to/file')) {
      // File exists
    }
  

Generating Application Example

Let’s create a sample Node.js application that utilizes the above ShellJS APIs. Suppose we want to create a script for managing project setup.

  
    const shell = require('shelljs');

    // Function to check dependencies
    function checkDependencies() {
      if (!shell.which('git')) {
        shell.echo('Sorry, this script requires git');
        shell.exit(1);
      }
    }

    // Function to clone repo and setup project
    function setupProject() {
      shell.echo('Cloning repository...');
      shell.exec('git clone https://github.com/user/repo.git');
      
      shell.cd('repo');
      shell.echo('Installing dependencies...');
      shell.exec('npm install');
      
      shell.echo('Project setup complete.');
    }

    // Run the functions
    checkDependencies();
    setupProject();
  

Conclusion

ShellJS is a powerful tool for Node.js developers, enabling them to use shell commands within their scripts efficiently. With the examples provided, you can automate various tasks in your development workflow. Whether it’s setting up projects, managing files, or executing shell commands, ShellJS can help streamline your processes.

Hash: e2e2e5605677a01350c0b7c18bea792a1f10e87dc5d5a33ed6fd670c537898e3

Leave a Reply

Your email address will not be published. Required fields are marked *