Facilitating the Spread of Knowledge and Innovation in Professional Software Development

Write for InfoQ


Choose your language

InfoQ Homepage News Zx - a Tool for Writing Better Scripts

Zx - a Tool for Writing Better Scripts

This item in japanese

Google recently released a new library called ZX, enabling developers to write CLI scripts using JavaScript without the hassle of dealing with Node.js directly.

CLI scripts are most often written in Bash. However, writing Bash scripts is not a trivial task, especially for developers who are not comfortable with the Linux command line.

While writing scripts using Node.js has been possible for a long time, interacting with executables and handling arguments and responses can be quite challenging and has limited the usage of JavaScript for such tasks.To address these challenges, Google has recently released zx, a Node.js executable that addresses the common pitfalls of writing JavaScript CLI scripts while also providing a set of sensible tools and libraries to speed up the development process.

To get started, install zx globally with npm using the following command:

npm i -g zx

Before starting to write zx scripts, two important prerequisites need to be highlighted.

First, we need to let the operating system know which interpreter is needed for our script. To do that, we use a special instruction called shebang (or hashbang). For zx scripts, we add the following line to the beginning of the file:

#!/usr/bin/env zx

Secondly, we need to indicate to the operating system that the text file we have written is an executable using

chmod +x ./<script name>

To help write meaningful CLI scripts, zx includes several tools that enable developers to interact with the user and the CLI. These include three built-in packages: fs which is used to interact with the file system, os which provides operating system-related utilities, and finally chalk which enables terminal string styling.

In addition, zx provides thin wrappers around commonly used Node.js commands to address common use cases such as fetching data, interacting with the user, and of course, executing CLI commands. For a full list of commands, see the official documentation.

As all wrapped commands return promises, it is recommended to use the JavaScript await operator. However, to enable top-level await support, developers need to use the .mjs file extension when saving the script file. Otherwise, using the await operator will require wrapping the script with an Immediately Invoked Function Expression.

It's worth mentioning that while zx is published under the Google GitHub user, it is currently maintained by Anton Medvedev and is not officially supported by Google. Google zx is released under the Apache License 2.0, and its source code is available on GitHub.

Rate this Article