### Install zx Source: https://github.com/google/zx/blob/main/docs/getting-started.md Provides instructions on how to install the zx package using npm. ```bash npm install zx ``` -------------------------------- ### Running zx Scripts Source: https://github.com/google/zx/blob/main/docs/getting-started.md Explains how to make zx scripts executable and run them directly, or how to execute them using the zx CLI. ```bash #!/usr/bin/env zx chmod +x ./script.mjs ./script.mjs ``` ```bash zx ./script.mjs ``` -------------------------------- ### Installing and Using Canary/Beta zx Builds Source: https://github.com/google/zx/blob/main/docs/faq.md Instructs users on how to install and utilize experimental versions of zx using `npm install zx@dev`. It also shows an example of running a beta build with specific options, including piping input. ```bash npm i zx@dev npx zx@dev --install --quiet <<< 'import _ from "lodash" /* 4.17.15 */; console.log(_.VERSION)' ``` -------------------------------- ### Setup Node.js and Bash Environment Source: https://github.com/google/zx/blob/main/docs/contribution.md Instructions for setting up the development environment for zx, including installing Node.js version 22 or higher and ensuring Bash is available. It suggests using version managers like Volta for Node.js and WSL or Git Bash for Windows users. ```shell # Install Node.js >= 22 manually or using a version manager like Volta # Example using Volta: # volta install node@22 # Ensure Bash is available (Linux/macOS have it by default) # For Windows, consider WSL or Git Bash ``` -------------------------------- ### Importing zx Globals Source: https://github.com/google/zx/blob/main/docs/getting-started.md Shows how to import zx globals explicitly for better IDE support, such as autocompletion in VS Code. ```js import 'zx/globals' ``` -------------------------------- ### Using ProcessOutput with $`command` Source: https://github.com/google/zx/blob/main/docs/getting-started.md Shows how the output of a ProcessOutput object is automatically trimmed and used as stdout when passed as an argument to another $`command`. ```js const date = await $`date` await $`echo Current date is ${date}.` ``` -------------------------------- ### Basic zx Script Execution Source: https://github.com/google/zx/blob/main/docs/getting-started.md Demonstrates executing shell commands, capturing output, and running commands in parallel using zx. It shows how to use the $`command` syntax for executing shell commands and awaiting their results. ```js #!/usr/bin/env zx await $`cat package.json | grep name` const branch = await $`git branch --show-current` await $`dep deploy --branch=${branch}` await Promise.all([ $`sleep 1; echo 1`, $`sleep 2; echo 2`, $`sleep 3; echo 3`, ]) const name = 'foo bar' await $`mkdir /tmp/${name}` ``` -------------------------------- ### Executing Shell Commands with $`command` Source: https://github.com/google/zx/blob/main/docs/getting-started.md Demonstrates the primary method of executing shell commands in zx using the $`command` template literal. It covers both asynchronous and synchronous execution, as well as automatic argument escaping. ```js const list = await $`ls -la` const dir = $.sync`pwd` ``` ```js const name = 'foo & bar' await $`mkdir ${name}` ``` ```js const flags = [ '--oneline', '--decorate', '--color', ] await $`git log ${flags}` ``` ```js const a1 = $`echo foo` const a2 = new Promise((resolve) => setTimeout(resolve, 20, ['bar', 'baz'])) await $`echo ${a1} ${a2}` // foo bar baz ``` -------------------------------- ### Handling Non-Zero Exit Codes Source: https://github.com/google/zx/blob/main/docs/getting-started.md Illustrates how zx throws a ProcessOutput error when a command returns a non-zero exit code, allowing for error handling. ```js try { await $`exit 1` } catch (p) { console.log(`Exit code: ${p.exitCode}`) console.log(`Error: ${p.stderr}`) } ``` -------------------------------- ### Install zx using bun Source: https://github.com/google/zx/blob/main/docs/setup.md Installs the zx package using bun. ```bash bun install zx ``` -------------------------------- ### ProcessOutput Class Source: https://github.com/google/zx/blob/main/docs/getting-started.md Defines the structure of the ProcessOutput class, which captures the standard output, standard error, signal, and exit code of a process. It also includes methods for converting the output to a string. ```ts class ProcessOutput { readonly stdout: string readonly stderr: string readonly signal: string readonly exitCode: number // ... toString(): string // Combined stdout & stderr. valueOf(): string // Returns .toString().trim() } ``` -------------------------------- ### Install zx from GitHub Source: https://github.com/google/zx/blob/main/docs/setup.md Installs zx directly from its GitHub repository using npm, either via the git URL or the GitHub package registry. ```bash # Install via git npm i google/zx npm i git@github.com:google/zx.git # Fetch from the GH pkg registry npm i --registry=https://npm.pkg.github.com @google/zx ``` -------------------------------- ### Install zx using brew Source: https://github.com/google/zx/blob/main/docs/setup.md Installs the zx package using Homebrew. ```bash brew install zx ``` -------------------------------- ### Install zx using jsr Source: https://github.com/google/zx/blob/main/docs/setup.md Installs the zx package from jsr.io using npx or deno. ```bash npx jsr add @webpod/zx deno add jsr:@webpod/zx # https://jsr.io/docs/using-packages ``` -------------------------------- ### Installing Dependencies with --install Source: https://github.com/google/zx/blob/main/docs/cli.md Demonstrates how to automatically install missing dependencies for a script by using the --install flag. ```js // script.mjs: import sh from 'tinysh' sh.say('Hello, world!') ``` ```bash zx --install script.mjs ``` ```js import sh from 'tinysh' // @^1 ``` -------------------------------- ### Install zx using pnpm Source: https://github.com/google/zx/blob/main/docs/setup.md Installs the zx package using pnpm. ```bash pnpm add zx ``` -------------------------------- ### Install zx using npm Source: https://github.com/google/zx/blob/main/docs/setup.md Installs the zx package using npm. Can be installed globally by adding the '-g' flag. ```bash npm install zx # add -g to install globally ``` -------------------------------- ### Install zx using yarn Source: https://github.com/google/zx/blob/main/docs/setup.md Installs the zx package using yarn. ```bash yarn add zx ``` -------------------------------- ### Install zx using deno Source: https://github.com/google/zx/blob/main/docs/setup.md Installs the zx package using deno. Requires additional permissions for read, sys, env, and run operations. ```bash deno install -A npm:zx # zx requires additional permissions: --allow-read --allow-sys --allow-env --allow-run ``` -------------------------------- ### Install zx@lite Source: https://github.com/google/zx/blob/main/docs/lite.md Installs the zx@lite package using npm. This command fetches the core zx functionality without additional dependencies or features. ```shell npm i zx@lite npm i zx@8.5.5-lite ``` -------------------------------- ### Replace ssh API with webpod Source: https://github.com/google/zx/blob/main/docs/migration-from-v7.md The built-in `ssh` API has been removed. Install the `webpod` package and import `ssh` from it to maintain similar functionality for remote shell access. ```js // import {ssh} from 'zx' ↓ import {ssh} from 'webpod' const remote = ssh('user@host') await remote`echo foo` ``` -------------------------------- ### Combined Piping Examples Source: https://github.com/google/zx/blob/main/docs/process-promise.md Illustrates various combinations of piping, including piping to transform streams, file streams, and back to processes. ```js const getUpperCaseTransform = () => new Transform({ transform(chunk, encoding, callback) { callback(null, String(chunk).toUpperCase()) }, }) // $ > stream (promisified) > $ const o1 = await $`echo "hello"` .pipe(getUpperCaseTransform()) .pipe($`cat`) o1.stdout // 'HELLO\n' // stream > $ const file = tempfile() await fs.writeFile(file, 'test') const o2 = await fs .createReadStream(file) .pipe(getUpperCaseTransform()) .pipe($`cat`) o2.stdout // 'TEST' ``` -------------------------------- ### Echo Hello World in ZX Source: https://github.com/google/zx/blob/main/test/fixtures/markdown-crlf.md A simple example demonstrating how to print 'Hello, world!' using the ZX shell scripting language. ZX allows you to write shell scripts in JavaScript. ```javascript echo`Hello, world!` ``` -------------------------------- ### Output Formatting: text(), buffer(), lines(), json() Source: https://github.com/google/zx/blob/main/docs/process-promise.md Provides examples of various output formatting methods available for ProcessPromise. These include getting output as text, raw buffer, an array of lines, or parsing JSON directly. ```js const p = $`echo 'foo\nbar'` await p.text() // foo\n\bar\n await p.text('hex') // 666f6f0a0861720a await p.buffer() // Buffer.from('foo\n\bar\n') await p.lines() // ['foo', 'bar'] // You can specify a custom lines delimiter if necessary: await $`touch foo bar baz; find ./ -type f -print0` .lines('\0') // ['./bar', './baz', './foo'] // If the output is a valid JSON, parse it in place: await $`echo '{"foo": "bar"}'` .json() // {foo: 'bar'} ``` -------------------------------- ### Enable PowerShell and Bash Source: https://github.com/google/zx/blob/main/docs/migration-from-v7.md Configure zx to use PowerShell or Bash. `usePowerShell()` enables PowerShell, while `useBash()` switches to Bash, which is the default. ```js import { usePowerShell, useBash } from 'zx' usePowerShell() // to enable powershell useBash() // switch to bash, the default ``` -------------------------------- ### zx CLI Helper Functions Source: https://github.com/google/zx/blob/main/docs/architecture.md Documentation for the helper functions used within the zx CLI, detailing their roles in script execution, dependency management, and context setup. ```APIDOC main() Initializes a preset from flags, env vars and pushes the reader. readScript() Fetches, parses and transforms the specified source into a runnable form. stdin reader, https loader and md transformer act right here. Deps analyzer internally relies on [depseek](https://www.npmjs.com/package/depseek) and inherits its limitations. runScript() Executes the script in the target context via async import(), handles temp assets after. ``` -------------------------------- ### Enable Modern PowerShell (v7+) Source: https://github.com/google/zx/blob/main/docs/migration-from-v7.md Use the `usePwsh()` helper to enable support for modern PowerShell versions (v7 and above). ```js import { usePwsh } from 'zx' usePwsh() ``` -------------------------------- ### Install zx Source: https://github.com/google/zx/blob/main/README.md Provides the command to install the zx package using npm. This is a prerequisite for using zx for shell scripting. ```bash npm install zx ``` -------------------------------- ### Customizing the Registry Source: https://github.com/google/zx/blob/main/docs/cli.md Explains how to specify a different npm registry for package installations. ```bash zx --registry=https://registry.yarnpkg.com script.mjs ``` -------------------------------- ### Using zx with GitHub Actions Source: https://github.com/google/zx/blob/main/docs/faq.md Provides a GitHub Actions workflow example demonstrating how to run zx scripts. It uses `npx zx` within a `run` step, passing the script content via a heredoc (`<<'EOF'`). The `FORCE_COLOR` environment variable is set for colored output. ```yaml jobs: build: runs-on: ubuntu-latest steps: - uses: actions/checkout@v4 - name: Build with zx env: FORCE_COLOR: 3 run: | npx zx <<'EOF' await $`...` EOF ``` -------------------------------- ### zx Project Contribution Workflow Source: https://github.com/google/zx/blob/main/docs/contribution.md Steps for contributing code to the zx project, including forking the repository, creating a new branch, making changes, writing tests, adhering to conventional commits, formatting code, running tests, and submitting a pull request. ```shell # Fork the repository # git clone https://github.com/google/zx.git # Create a new branch # git checkout -b my-feature-branch # Make your changes # ... # Ensure test coverage is >= 98% # npm run test:coverage # Format code # npm run fmt # Commit changes using conventional commits # git commit -m "feat: add new feature" # Push changes to your fork # git push origin my-feature-branch # Create a pull request on GitHub ``` -------------------------------- ### Setting the Shell via Environment Variable Source: https://github.com/google/zx/blob/main/docs/shell.md This example demonstrates how to set the shell for zx execution using an environment variable. It shows the common practice of prefixing the zx command with the environment variable assignment. ```bash ZX_SHELL=/bin/zsh zx script.js ``` -------------------------------- ### Attaching Profiles and Aliases with zx Source: https://github.com/google/zx/blob/main/docs/faq.md Details how to include shell aliases and functions in zx scripts by prepending directives to `$.prefix`. This is necessary because `child_process` typically doesn't inherit these by default. The example shows sourcing `nvm`. ```js $.prefix += 'export NVM_DIR=$HOME/.nvm; source $NVM_DIR/nvm.sh; ' await $`nvm -v` ``` -------------------------------- ### Preferring Local Packages Source: https://github.com/google/zx/blob/main/docs/cli.md Demonstrates the --prefer-local flag to prioritize locally installed Node.js modules and binaries. ```bash zx --prefer-local=/external/node_modules/or/nm-root script.mjs ``` -------------------------------- ### Start CLI Spinner with spinner() Source: https://github.com/google/zx/blob/main/docs/api.md Starts a simple CLI spinner to indicate ongoing operations. It can be used with a callback function for a long-running command or with a custom message. The spinner is disabled by default in CI environments. ```js await spinner(() => $`long-running command`) // With a message. await spinner('working...', () => $`sleep 99`) ``` -------------------------------- ### Prefer Local Binaries Source: https://github.com/google/zx/blob/main/docs/configuration.md Configures ZX to prioritize executables found in `node_modules/.bin` over globally installed ones. Can also accept a specific path or an array of paths to search. ```javascript $.preferLocal = true await $`c8 npm test` ``` ```javascript $.preferLocal = '/some/to/bin' $.preferLocal = ['/path/to/bin', '/another/path/bin'] ``` -------------------------------- ### Reading from Process Stdout Source: https://github.com/google/zx/blob/main/docs/process-promise.md Explains how to read from the process's standard output using the `stdout` getter, which returns a readable stream. It shows an example of iterating over chunks of data. ```js const p = $`npm init` for await (const chunk of p.stdout) { echo(chunk) } ``` -------------------------------- ### Setting the Shell via CLI Flag Source: https://github.com/google/zx/blob/main/docs/shell.md This example illustrates how to specify the shell to be used by zx via a command-line interface flag. It shows the syntax for passing the shell path when executing a script. ```bash zx --shell /bin/zsh script.js ``` -------------------------------- ### Synchronize Process CWD Source: https://github.com/google/zx/blob/main/docs/migration-from-v7.md Restore the legacy v7 behavior of synchronizing the process's current working directory (cwd) between `$` invocations by calling `syncProcessCwd()`. ```js import { syncProcessCwd } from 'zx' syncProcessCwd() // restores legacy v7 behavior ``` -------------------------------- ### zx Entry Points Source: https://github.com/google/zx/blob/main/docs/setup.md Describes the different entry points provided by zx for various use cases, including the main export, global scope population, CLI execution, and core utilities. ```js * `zx` – the main entry point, provides all the features. * `zx/global` – to populate the global scope with zx functions. * `zx/cli` – to run zx scripts from the command line. * `zx/core` – to use zx template spawner as part of 3rd party libraries with alternating set of utilities. ``` -------------------------------- ### Execute Shell Commands with ZX Source: https://github.com/google/zx/blob/main/test/fixtures/markdown.md Demonstrates executing shell commands asynchronously using ZX's backtick syntax. It shows how to capture command output and use template literals for dynamic command construction. ```javascript await $`whoami` await $`echo ${__dirname}` ``` ```javascript await $`echo "tilde"` ``` -------------------------------- ### Basic Script Execution Source: https://github.com/google/zx/blob/main/docs/cli.md Demonstrates the fundamental way to execute a script using the zx CLI. ```sh zx script.mjs ``` -------------------------------- ### Ignored CSS code block Source: https://github.com/google/zx/blob/main/docs/markdown.md Example of a CSS code block within a Markdown file, which ZX will ignore and not execute. ```css body .hero { margin: 42px; } ``` -------------------------------- ### Piping with zx Source: https://github.com/google/zx/blob/main/docs/architecture.md Demonstrates how to use the pipe() function in zx to chain commands and capture output from stdout and stderr. It also shows how the internal recorder allows binding processes even after they have settled. ```ts const p = $`cmd` const crits = await p.pipe.stderr`grep critical` const names = await p.pipe.stdout`grep name` ``` ```ts const onData = (chunk: string | Buffer) => from.write(chunk) const fill = () => { for (const chunk of source) from.write(chunk) } ee.once(source, () => { fill() // 1. Pulling previous records ee.on(source, onData) // 2. Listening for new data }).once('end', () => { ee.removeListener(source, onData) from.end() }) ``` ```ts const p = $`cmd` await p await p.pipe`grep name` // Still works, but `p` is settled ``` -------------------------------- ### zx package.json Build Scripts Source: https://github.com/google/zx/blob/main/docs/architecture.md Defines the npm scripts for building the zx project, including prebuild cleanup, main build process, JavaScript bundling, vendor file creation, test generation, Docker image building, and JSR publishing. ```json { "prebuild": "rm -rf build", "build": "npm run build:js && npm run build:dts && npm run build:tests", "build:js": "node scripts/build-js.mjs --format=cjs --hybrid --entry=src/*.ts:!src/error.ts:!src/repl.ts:!src/md.ts:!src/log.ts:!src/globals-jsr.ts:!src/goods.ts && npm run build:vendor", "build:vendor": "node scripts/build-js.mjs --format=cjs --entry=src/vendor-*.ts --bundle=all --external='./internals.ts'", "build:tests": "node scripts/build-tests.mjs", "build:dts": "tsc --project tsconfig.json && rm build/repl.d.ts build/globals-jsr.d.ts && node scripts/build-dts.mjs", "build:dcr": "docker build -f ./dcr/Dockerfile . -t zx", "build:jsr": "node scripts/build-jsr.mjs" } ``` -------------------------------- ### Await Chained Streams Source: https://github.com/google/zx/blob/main/docs/process-promise.md Chained streams created with pipe() are thenable, allowing them to be awaited. This example demonstrates piping to a transform stream and then to a file write stream. ```js const p = $`echo "hello"` .pipe(getUpperCaseTransform()) .pipe(fs.createWriteStream(tempfile())) // <- stream const o = await p ``` -------------------------------- ### Switch shell in zx Source: https://github.com/google/zx/blob/main/docs/setup.md Shows how to switch the default shell used by zx between Bash, PowerShell, and pwsh (PowerShell Core). ```js import { useBash, usePowerShell, usePwsh } from 'zx' usePowerShell() // Use PowerShell.exe usePwsh() // Rely on pwsh binary (PowerShell v7+) useBash() // Switch back to bash ``` -------------------------------- ### zx Build Scripts Overview Source: https://github.com/google/zx/blob/main/docs/architecture.md This section outlines the primary build scripts used in the zx project, detailing their purpose in packaging and preparing the library for distribution. These scripts leverage tools like esbuild and dts-bundle-generator. ```markdown | Script | Description | |----------------------------------------------------------------------------------------------|------------------------------------------------------------------------| | [`./scripts/build-dts.mjs`](https://github.com/google/zx/blob/main/scripts/build-dts.mjs) | Extracts and merges 3rd-party types, generates `dts` files. | | [`./scripts/build-js.mjs`](https://github.com/google/zx/blob/main/scripts/build-js.mjs) | Produces [hybrid bundles](./setup#hybrid) for each package entry point | | [`./scripts/build-jsr.mjs`](https://github.com/google/zx/blob/main/scripts/build-jsr.mjs) | Builds extra assets for [JSR](https://jsr.io/@webpod/zx) publishing | | [`./scripts/build-tests.mjs`](https://github.com/google/zx/blob/main/scripts/build-test.mjs) | Generates autotests to verify exports consistency | ``` -------------------------------- ### zx package.json Testing Scripts - Pretest and Unit/Coverage Source: https://github.com/google/zx/blob/main/docs/architecture.md Configuration for pre-testing and unit testing in zx. The 'pretest' script ensures the project is built before tests run. Unit tests focus on implementation correctness and coverage is monitored using c8. ```json { "pretest": "npm run build" } { "test:unit": "node --experimental-transform-types ./test/all.test.js", "test:coverage": "c8 -c .nycrc --check-coverage npm run test:unit" } ``` -------------------------------- ### Configure Verbose and Quiet Output Source: https://github.com/google/zx/blob/main/docs/migration-from-v7.md Control the verbosity of zx output. By default, $.verbose is false, but errors are still printed. Set $.quiet to true to suppress all output. ```js $.verbose = true // everything works like in v7 $.quiet = true // to completely turn off logging ``` -------------------------------- ### Prefixing and Postfixing Commands Source: https://github.com/google/zx/blob/main/docs/cli.md Illustrates how to add commands to the beginning (--prefix) or end (--postfix) of every command executed by zx. ```bash zx --prefix='echo foo;' --postfix='; echo bar' script.mjs ``` -------------------------------- ### Standard Input/Output Configuration Source: https://github.com/google/zx/blob/main/docs/process-promise.md Illustrates how to specify standard input, output, and error streams for a process using the stdio method. Shows default behavior and preset syntax. ```javascript const h$ = $({halt: true}) const p1 = h$`read`.stdio('inherit', 'pipe', null).run() const p2 = h$`read`.stdio('pipe').run() // sets ['pipe', 'pipe', 'pipe'] ``` ```javascript await $({stdio: ['pipe', 'pipe', 'pipe']})`read` ``` -------------------------------- ### File Path and Filename Handling with ZX Source: https://github.com/google/zx/blob/main/test/fixtures/markdown.md Shows how to use ZX with the 'chalk' library to print file path information, specifically the filename, with colored output. ```javascript console.log(chalk.yellowBright(__filename)) ``` ```javascript await import('chalk') ``` -------------------------------- ### Potential Injection with Escaping Source: https://github.com/google/zx/blob/main/docs/quotes.md Illustrates a potential security risk where Zx's automatic escaping might lead to unintended command execution if not handled carefully. This example shows how a malicious string could be partially executed. ```ts const args = ['param && echo bar'] const p = $`echo --foo=$'${args}'` (await p).stdout // '--foo=$param\nbar\n' ``` -------------------------------- ### Run zx scripts with Docker Source: https://github.com/google/zx/blob/main/docs/setup.md Demonstrates running zx scripts within a Docker container, pulling the image from ghcr.io and executing commands or scripts. ```shell docker pull ghcr.io/google/zx:8.5.0 docker run -t ghcr.io/google/zx:8.5.0 -e="await $({verbose: true})\`echo foo\`" docker run -t -i -v ./:/script ghcr.io/google/zx:8.5.0 script/t.js ``` -------------------------------- ### Run script with npx Source: https://github.com/google/zx/blob/main/docs/setup.md Executes a JavaScript script using npx, either with the latest zx version or a specific pinned version. ```bash npx zx script.js # run script without installing the zx package npx zx@8.6.0 script.js # pin to a specific zx version ``` -------------------------------- ### Alternative Execution Methods Source: https://github.com/google/zx/blob/main/docs/cli.md Shows alternative methods to run zx scripts using npx or node with specific imports. ```sh npx zx script.mjs ``` ```sh node -r zx/globals script.mjs ``` ```sh node --import zx/globals script.mjs ``` -------------------------------- ### Process Information with ps Source: https://github.com/google/zx/blob/main/docs/api.md Provides cross-platform process listing capabilities using the `@webpod/ps` package. Allows looking up processes by command, retrieving process trees, and checking recursive relationships. ```js const all = await ps.lookup() const nodejs = await ps.lookup({ command: 'node' }) const children = await ps.tree({ pid: 123 }) const fulltree = await ps.tree({ pid: 123, recursive: true }) ``` -------------------------------- ### zx package.json Testing Scripts - Integration and Size Source: https://github.com/google/zx/blob/main/docs/architecture.md Scripts for integration testing of different build outputs (npm, JSR, DCR) and for checking bundle code duplication issues using size-limit. ```json { "test:npm": "node ./test/it/build-npm.test.js", "test:jsr": "node ./test/it/build-jsr.test.js", "test:dcr": "node ./test/it/build-dcr.test.js" } { "test:size": "size-limit" } ``` -------------------------------- ### Using Environment Variables for Configuration Source: https://github.com/google/zx/blob/main/docs/cli.md Shows how to set zx options using environment variables, providing an alternative to command-line flags. ```bash ZX_VERBOSE=true ZX_SHELL='/bin/bash' zx script.mjs ``` ```yaml steps: - name: Run script run: zx script.mjs env: ZX_VERBOSE: true ZX_SHELL: '/bin/bash' ``` -------------------------------- ### Importing zx Functions Source: https://github.com/google/zx/blob/main/docs/faq.md Shows how to import the `$` function and other utilities from the 'zx' package into other Node.js scripts. This allows for modularity and reuse of zx's shell execution capabilities. ```js #!/usr/bin/env node import {$} from 'zx' await $`date` ``` -------------------------------- ### Specifying an Environment File Source: https://github.com/google/zx/blob/main/docs/cli.md Demonstrates how to load environment variables from a specified file using the --env option. ```bash zx --env=/path/to/some.env script.mjs ``` ```bash `--cwd='/foo/bar' --env='../.env'` → `/foo/.env` ``` -------------------------------- ### Correct Home Directory Expansion with `os.homedir()` Source: https://github.com/google/zx/blob/main/docs/quotes.md Demonstrates the correct way to expand the home directory in Zx by using `os.homedir()`. This ensures the path is correctly resolved. ```js await $`ls ${os.homedir()}/Downloads` // Correct ``` -------------------------------- ### Enable Bash Environment with useBash() Source: https://github.com/google/zx/blob/main/docs/api.md Sets the default shell to `bash` and configures the quoting mechanism to use the `quote` function, optimizing for bash command execution. ```js useBash() ``` -------------------------------- ### zx package.json Testing Scripts - License and Security Source: https://github.com/google/zx/blob/main/docs/architecture.md Scripts for checking license compliance and supply chain security vulnerabilities, including running npm audit. ```json { "test:license": "node ./test/extra.test.js", "test:audit": "npm audit fix", "test:workflow": "zizmor .github/workflows -v -p --min-severity=medium" } ``` -------------------------------- ### zx package.json Testing Scripts - Smoke Tests (Runtimes and OS) Source: https://github.com/google/zx/blob/main/docs/architecture.md Scripts to test zx compatibility across various runtimes (Bun, Node.js) and operating systems (Windows). ```json { "test:smoke:bun": "bun test ./test/smoke/bun.test.js && bun ./test/smoke/node.test.mjs", "test:smoke:win32": "node ./test/smoke/win32.test.js", "test:smoke:deno": "deno test ./test/smoke/deno.test.js --allow-read --allow-sys --allow-env --allow-run" } ``` -------------------------------- ### Executing Scripts from Stdin Source: https://github.com/google/zx/blob/main/docs/cli.md Illustrates how to pipe script content to the zx CLI via standard input. ```js zx << 'EOF' await $`pwd` EOF ``` -------------------------------- ### zx package.json Testing Scripts - Quality and Type Checking Source: https://github.com/google/zx/blob/main/docs/architecture.md Scripts for maintaining code quality through static analysis (prettier, madge for circular dependencies) and type checking using tsd. ```json { "fmt:check": "prettier --check .", "test:circular": "madge --circular src/*" } { "test:types": "tsd" } ``` -------------------------------- ### ZX Project Dependencies Source: https://github.com/google/zx/blob/main/docs/setup.md This snippet outlines the project's compatibility and dependency requirements. It specifies the TypeScript version, bundling tool, and necessary type definitions. ```typescript /// /// // Compatible with TS 4.0 and later. // Libdefs are bundled via dts-bundle-generator. ``` -------------------------------- ### zx Hybrid Package and TypeScript Support Source: https://github.com/google/zx/blob/main/docs/setup.md Illustrates zx's hybrid package structure (CJS/ESM) and the need for TypeScript type definitions for fs-extra and Node.js. ```js import { $ } from 'zx' const { $ } = require('zx') ``` ```bash npm i -D @types/fs-extra @types/node ``` ```ts import { type Options } from 'zx' const opts: Options = { quiet: true, timeout: '5s' } ``` -------------------------------- ### AbortController Integration Source: https://github.com/google/zx/blob/main/docs/process-promise.md Demonstrates how to use AbortController with zx processes to terminate them. Shows automatic creation of AbortController when not provided and how to abort with a reason. ```javascript const ac = new AbortController() const {signal} = ac const p = $({signal})`sleep 999` setTimeout(() => ac.abort('reason'), 100) await p ``` ```javascript const p = $`sleep 999` const {signal} = p const res = fetch('https://example.com', {signal}) p.abort('reason') ``` -------------------------------- ### Executing Markdown Files Source: https://github.com/google/zx/blob/main/docs/cli.md Shows how zx can execute code blocks within Markdown files. ```bash zx docs/markdown.md ``` -------------------------------- ### Controlling zx Verbose and Quiet Output Source: https://github.com/google/zx/blob/main/docs/faq.md Explains how to manage the verbosity of zx's internal logger using `$.verbose` and `$.quiet` flags. It covers global settings, in-place overrides for specific commands, and how to replace the default logger entirely. ```js // Global debug mode on $.verbose = true await $`echo hello` // Suppress the particular command await $`echo fobar`.quiet() // Suppress everything $.quiet = true await $`echo world` // Turn on in-place debug await $`echo foo`.verbose() // globally $.log = (entry) => { switch (entry.kind) { case 'cmd': console.log('Command:', entry.cmd) break default: console.warn(entry) } } // or in-place $({log: () => {}})`echo hello` ``` -------------------------------- ### zx Shell Factory and ProcessPromise Source: https://github.com/google/zx/blob/main/docs/architecture.md Demonstrates the TypeScript interface for the zx shell factory '$', including synchronous and asynchronous execution, and options for process management. It also outlines the structure for ProcessPromise, which represents and operates child processes. ```ts interface Shell< S = false, R = S extends true ? ProcessOutput : ProcessPromise, > { (pieces: TemplateStringsArray, ...args: any[]): R = Partial, R = O extends { sync: true } ? Shell : Shell>(opts: O): R sync: { (pieces: TemplateStringsArray, ...args: any[]): ProcessOutput (opts: Partial>): Shell } } $`cmd ${arg}` // ProcessPromise $(opts)`cmd ${arg}` // ProcessPromise $.sync`cmd ${arg}` // ProcessOutput $.sync(opts)`cmd ${arg}` // ProcessOutput ``` ```ts const storage = new AsyncLocalStorage() const getStore = () => storage.getStore() || defaults function within(callback: () => R): R { return storage.run({ ...getStore() }, callback) } // Inside $ factory ... const opts = getStore() if (!Array.isArray(pieces)) { return function (this: any, ...args: any) { return within(() => Object.assign($, opts, pieces).apply(this, args)) } } ``` -------------------------------- ### Basic zx Script Execution Source: https://github.com/google/zx/blob/main/README.md Demonstrates executing shell commands within a zx script. It shows how to pipe output, capture command output into variables, and use template literals for dynamic command construction. Dependencies include Node.js and zx. ```js #!/usr/bin/env zx await $`cat package.json | grep name` const branch = await $`git branch --show-current` await $`dep deploy --branch=${branch}` await Promise.all([ $`sleep 1; echo 1`, $`sleep 2; echo 2`, $`sleep 3; echo 3`, ]) const name = 'foo bar' await $`mkdir /tmp/${name}` ``` -------------------------------- ### Run ZX script Source: https://github.com/google/zx/blob/main/docs/markdown.md Illustrates the command to execute a ZX script file named 'script.md'. ```bash zx script.md ``` -------------------------------- ### Configure Logging Source: https://github.com/google/zx/blob/main/docs/configuration.md Allows customization of the logging behavior, including the output stream and formatters for different log entry kinds. Requires importing `LogEntry` and `log` from `zx/core`. ```typescript import {LogEntry, log} from 'zx/core' $.log = (entry: LogEntry) => { switch (entry.kind) { case 'cmd': // for example, apply custom data masker for cmd printing process.stderr.write(masker(entry.cmd)) break default: log(entry) } } ``` ```typescript $.log.output = process.stdout ``` ```typescript $.log.formatters = { cmd: (entry: LogEntry) => `CMD: ${entry.cmd}`, fetch: (entry: LogEntry) => `FETCH: ${entry.url}` } ``` -------------------------------- ### Bash Variable Assignment and Usage Source: https://github.com/google/zx/blob/main/test/fixtures/markdown.md A bash script snippet demonstrating variable assignment using command substitution and how to echo the variable's content, ensuring proper quoting for handling spaces. ```bash VAR=$(echo hello) echo "$VAR" ``` -------------------------------- ### Writing to Process Stdin Source: https://github.com/google/zx/blob/main/docs/process-promise.md Demonstrates how to interact with the process's standard input using the `stdin` getter, which returns a writable stream. It highlights the need to end the stream after writing. ```js const p = $`while read; do echo $REPLY; done` p.stdin.write('Hello, World!\n') p.stdin.end() ``` -------------------------------- ### Time-Delayed Piping Source: https://github.com/google/zx/blob/main/docs/process-promise.md Demonstrates piping a process at different stages of its execution, buffering and processing chunks in order. ```js const result = $`echo 1; sleep 1; echo 2; sleep 1; echo 3` const piped1 = result.pipe`cat` let piped2 setTimeout(() => { piped2 = result.pipe`cat` }, 1500) (await piped1).toString() // '1\n2\n3\n' (await piped2).toString() // '1\n2\n3\n' ``` -------------------------------- ### ProcessPromise Execution Source: https://github.com/google/zx/blob/main/docs/process-promise.md Demonstrates the basic usage of the $ function to create and execute a ProcessPromise. It shows how to capture the ProcessPromise and await its resolution to a ProcessOutput. ```js const p = $`command` // ProcessPromise const o = await p // ProcessOutput ``` -------------------------------- ### Command-Line Argument Parsing with minimist Source: https://github.com/google/zx/blob/main/docs/api.md Integrates the `minimist` package for parsing command-line arguments. Allows customization of parsing behavior through options like `boolean`, `alias`, etc. ```js const argv = minimist(process.argv.slice(2), {}) const myCustomArgv = minimist(process.argv.slice(2), { boolean: [ 'force', 'help', ], alias: { h: 'help', }, }) ``` -------------------------------- ### Executing a Command with ZX Source: https://github.com/google/zx/blob/main/docs/process-output.md Demonstrates how to execute a shell command using ZX and capture its output as a ProcessOutput object. ```typescript const p = $`command` // ProcessPromise const o = await p // ProcessOutput ``` -------------------------------- ### Asynchronous Iteration over Stdout Source: https://github.com/google/zx/blob/main/docs/process-promise.md Demonstrates how to use the `Symbol.asyncIterator` to iterate over the process's standard output line by line. It also shows how to specify a custom delimiter for iteration. ```js const p = $`echo "Line1\nLine2\nLine3"` for await (const line of p) { console.log(line) } // Custom delimiter can be specified: for await (const line of $({ delimiter: '\0' })`touch foo bar baz; find ./ -type f -print0`) { console.log(line) } ``` -------------------------------- ### Executing Remote Scripts Source: https://github.com/google/zx/blob/main/docs/cli.md Demonstrates executing a script by providing a URL as the argument. ```bash zx https://medv.io/game-of-life.js ``` -------------------------------- ### Execute Shell Command with zx Source: https://github.com/google/zx/blob/main/docs/lite.md Demonstrates how to execute a shell command ('echo foo') using the zx library in JavaScript. It utilizes the '$' template literal for seamless command execution. ```javascript import { $ } from 'zx' await $`echo foo` ``` -------------------------------- ### Importing modules in ZX Source: https://github.com/google/zx/blob/main/docs/markdown.md Shows how to import external modules, such as 'chalk', within a ZX script using the 'await import()' syntax. ```js await import('chalk') ```