google / zx

A tool for writing better scripts

Home Page:https://npmjs.com/package/zx

Geek Repo:Geek Repo

Github PK Tool:Github PK Tool

Feature request: replicate Node's -e/--eval flag

nicholaides opened this issue · comments

The node executable has the -e/--eval flag, which takes an argument from the command line and executes it as code. If zx had this, it would make it easier to use zx in other non-zx scripts, because currently, it's quite difficult to write an an inline zx script that takes data from stdin.

Example

E.g. I would love to be able to do something like this inside a bash (or otherwise) script:

curl https://exmaple.com/somedata | base64 -d | zx -e "
    // some zx code that uses data from stdin
"

Currently, this doesn't work because zx treats data coming in from stdin as code.

Current alternatives

Currently, the other options for quickly adding a stdin-reading zx script to a shell script:

Put zx script in another file and call it from the shell script

e.g. put zx code in process-the-data.js and do this:

curl https://exmaple.com/somedata | base64 -d | zx process-the-data.js

With this approach, my script is less self-contained. I can't as easily share my script it with my team by passing a file, dropping it in a gist, or pasting it into Slack.

Write data or code to a tempfile and pass the path of the tempfile to the zx script

This works, but seems like it shouldn't be necessary because pipes exist.

Utilize bash fd/coproc features, or mess with file descriptors

E.g., instead of piping data to zx's standard in, you can do this in bash (but not in sh):

zx - <(curl https://example.com) <<CODE
  const fdPath = process.argv[process.argv.length - 1]
  const data = fs.readFileSync(fdPath).toString()
  // do something with this data
CODE

In this example, rather than pass data to our zx script via stdin, we redirect it to a file descriptor and pass the path to our zx script as an argument.

This seems more complicated than it should be and is not even supported in some shells.

Non-alternative: bash redirect to a file descriptor path

I thought maybe we can redirect cat HEREDOC code to a file descriptor path and pass that into zx, but that doesn't, because zx appends .mjs to the file descriptor path (/dev/fd/63 in my case) and then complains that the file doesn't exist.

curl http://some-data | zx <(cat <<CODE
  console.log(42)
CODE
)

Other shells/script interpreters

How other shells and interpreters accept code from command line arguments:

shell flag
Node -e/--eval
ts-node -e/--eval
Ruby -e
Perl -e
Deno eval (e.g. deno eval 'console.log(42)')
Bash -c
Zsh -c
Dash -c

Really nice idea. Let’s add -e&—eval.

ezoic increase your site revenue