Home >Web Front-end >JS Tutorial >How to Write Shell Scripts in Node with Google's zx Library

How to Write Shell Scripts in Node with Google's zx Library

Lisa Kudrow
Lisa KudrowOriginal
2025-02-09 09:59:12941browse

This article explores Google's zx library, a powerful tool for streamlining shell scripting within Node.js projects. We'll build a command-line utility to bootstrap new Node.js projects, showcasing zx's capabilities.

How to Write Shell Scripts in Node with Google's zx Library

Key Advantages of Google's zx:

  • Simplifies shell scripting in Node.js using familiar JavaScript syntax.
  • Handles child process creation, stdout, and stderr efficiently.
  • Provides helpful utilities like $ (for command execution), cd(), question(), and access to popular libraries (e.g., chalk, minimist, fetch, fs-extra).
  • Promotes best practices: using ECMAScript Modules and local dependency management.
  • TypeScript compatibility (with minor configuration adjustments).

The Challenge of Traditional Shell Scripting:

Traditional shell scripting (Bash, zsh) can be cumbersome. Managing child processes, escaping arguments, and handling stdout/stderr adds complexity. While Bash offers built-in features, its syntax can be less intuitive for complex logic or user input handling. Node.js, while offering core modules and JavaScript's flexibility, requires manual child process management, making it less straightforward.

Google's zx: A Solution:

zx elegantly solves these problems. It wraps child process management and streamlines I/O handling.

Prerequisites:

  • Basic JavaScript and Node.js knowledge.
  • Terminal command familiarity.
  • Node.js >= v14.13.1.

The complete code is available on GitHub.

How zx Works:

The core function is $. For example:

<code class="language-javascript">import { $ } from "zx";

await $`ls`;</code>

This executes ls and captures output. zx utilizes tagged template literals for a clean syntax. Other useful functions include cd() for changing directories and question() for user input. It also integrates popular libraries like chalk (for colored output) and minimist (for command-line argument parsing).

Hello World with zx:

  1. Create a project: mkdir zx-project && cd zx-project && npm init -y
  2. Install zx: npm install --save-dev zx
  3. Create hello.mjs:
<code class="language-javascript">#! /usr/bin/env node
import { $ } from "zx";
$.verbose = false; // Suppress command echoing
const output = (await $`ls`).stdout.trim(); // Trim extra newline
console.log(output);</code>
  1. Make it executable: chmod u x hello.mjs
  2. Run: ./hello.mjs

zx with TypeScript:

TypeScript requires a tsconfig.json (e.g., "compilerOptions": {"target": "es2017", "module": "commonjs"}) and wrapping await in an IIFE:

<code class="language-javascript">import { $ } from "zx";

await $`ls`;</code>

Building a Project Bootstrapper:

Let's create a tool (bootstrap-tool.mjs) that automates project setup:

  1. Import necessary modules: import { $, argv, cd, chalk, fs, question } from "zx"; import path from "path"; import which from "which";
  2. Error handling function: function exitWithError(msg) { console.error(chalk.red(msg)); process.exit(1); }
  3. Check for required programs (git, node, npx): async function checkRequiredProgramsExist(programs) { ... }
  4. Handle --directory argument: Check if it exists and is a valid directory, then cd() into it.
  5. Check global Git settings (user.name, user.email).
  6. Initialize Git: await $git init;
  7. Generate package.json (using npm init -y), prompt for module system (commonjs or module), and update package.json.
  8. Prompt for and install npm packages (with validation).
  9. Generate configuration files (.gitignore, EditorConfig, Prettier, ESLint) using npx gitignore and npx mrm.
  10. Generate a basic README.md.
  11. Commit changes to Git.

This comprehensive bootstrapper significantly streamlines project initialization. Further enhancements could include automatic directory creation, open-source project features (license, Contributor Covenant), and GitHub repository automation.

Frequently Asked Questions (FAQs):

The provided FAQs section is already comprehensive and well-written. No changes are needed.

The above is the detailed content of How to Write Shell Scripts in Node with Google's zx Library. For more information, please follow other related articles on the PHP Chinese website!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn