DEV Community

Cover image for Bash scripts with node?
Giuliano1993
Giuliano1993

Posted on

Bash scripts with node?

Good morning, everyone, and happy MonDEV! ☕

How was your weekend? Can you feel the Holiday spirit starting to fill the air? It's certainly strong here, and in fact, this will be the last newsletter of the year before taking a bit of a break (and preparing lots of new content for you 😉).

But before we head towards the end of the year, today, I want to introduce you to a fantastic tool that I discovered entirely by chance! Often, we find ourselves wanting to automate some of the tasks we perform more frequently or needing to programmatically execute operations that would take very shorter time to be executed from the terminal.

While we have, on one hand, the possibility to write bash scripts, it is true that more complex flows, become intricate to develop, unless you're a bash pro. On the other hand, we also have the option to perform those operations in our preferred language, but in that case, the immediacy provided by bash is often lacking.

Right in the middle of this dilemma, our tool for today steps in to help!
Directly from our dear big G, we have ZX.

What is it? ZX is a wrapper that allows you to write bash scripts within .mjs files! Once installed globally, you can run the mjs files like actual bash scripts, while simultaneously leveraging the power of JS syntax we are accustomed to, such as await or try-catch blocks.

A series of APIs are also provided to interact with the entire bash environment in an extremely natural and convenient way, working on stdin, stdout, providing object-style access to arguments... in short, with ZX, you have a whole toolbox to work with bash more comfortably!

Let's quickly look at an example to see what the code looks like:

import 'zx/globals';
try {
    // Create a folder and...
    await $`mkdir -p ./projects/${argv.name}`;
    
    // ...enter it to execute the next commands
    cd(`./projects/${argv.name}`);
    
    // Initialize an npm project
    await $`npm init -y`;
    
    // Create the index.js and populate it
    await $`touch index.js`;
    await $`echo "console.log('Hello, World!')" > index.js`;
    
    // Do the same for the readme
    await $`touch README.md`;
    await $`echo "# ${argv.name}" > README.md`;
    
} catch (e) {

    // In case of an error, we can handle it in JS instead of presenting the default bash error
    console.log(`Exit code: ${e.exitCode}`)
    console.log(`Error: ${e.stderr}`)
}
Enter fullscreen mode Exit fullscreen mode

What do you think? Did you know this tool? If, like me, you are obsessed with minimizing repetitive work, I'm sure you should take a look 😉

With this gem, the newsletter takes a break for the Christmas holidays! I wish you a good start to the week, happy holidays, and a great start to the new year! We'll catch up on January 8th!

As always, Happy Coding 0_1

Top comments (0)