zx
概要
インストール
shell# pnpm
$ pnpm add -D zx
# npm
$ npm install --save-dev zx
基本的な使い方
*.mjs
形式のファイルにスクリプトを記述します
script.mjs// $`...`によってコマンドを実行
// await $`...`の戻り値として`CommandOutput`オブジェクトが返却されます
const output = await $`cat package.json | jq .devDependencies`;
// echo`...`で標準出力へメッセージを出力できます
// echo`...`には`CommandOutput`を渡すこともできます
echo`Result: ${output}`;
その後、以下のコマンドでスクリプトを実行できます
shell$ pnpm exec zx script.mjs
API
ProcessPromise
$
によって返却されます
.pipe()
メソッドを使うと、標準出力を
Writable
(
node:stream)へリダイレクトされることができます
javascriptimport { createWriteStream } from "node:fs";
await $`cat package.json | jq .devDependencies`.pipe(createWriteStream("deps.txt"));
// ProcessPromiseをpipeすることも可能です
const result = await $`cat package.json`.pipe($`jq .devDependencies`);
echo(result);
stdin
/
stdout
などのプロパティから、サブプロセスの標準入出力へアクセスできます (これらのプロパティは
node:streamの
Stream
です)
javascriptconst res = await fetch("http://localhost:8000/");
const json = await res.json();
shell$ pnpm exec zx --repl
# REPLの起動後、コマンドの実行などが行えます
❯ await $`cat package.json | jq .devDependencies`
リンク