zx
#shell #node-fetch #node:child_process #Node.js
概要
Node.jsでスクリプトを記述するためのヘルパーライブラリ
Googleによって開発されています
インストール
code:shell
# pnpm
$ pnpm add -D zx
# npm
$ npm install --save-dev zx
基本的な使い方
※pnpm execは適宜npxやyarnなどに置き換えください
*.mjs形式のファイルにスクリプトを記述します
code:script.mjs
// $...によってコマンドを実行
// await $...の戻り値としてCommandOutputオブジェクトが返却されます
const output = await $cat package.json | jq .devDependencies;
// echo...で標準出力へメッセージを出力できます
// echo...にはCommandOutputを渡すこともできます
echoResult: ${output};
その後、以下のコマンドでスクリプトを実行できます
code:shell
$ pnpm exec zx script.mjs
API
ProcessPromise
$によって返却されます
.pipe()メソッドを使うと、標準出力をWritable(node:stream)へリダイレクトされることができます
code:javascript
import { 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です)
fetch
zxにはnode-fetchが組み込まれていて、fetch()が利用できます
code:javascript
const res = await fetch("http://localhost:8000/");
const json = await res.json();
REPLの起動
code:shell
$ pnpm exec zx --repl
# REPLの起動後、コマンドの実行などが行えます
❯ await $cat package.json | jq .devDependencies
~/.zx_repl_historyにヒストリーが保存されます (src/repl.ts#L34)
zxを使っているプロジェクト
graphile-worker - スクリプトの記述に使われている
リンク
dax, Bun Shell, zxの比較