Security News
JavaScript Leaders Demand Oracle Release the JavaScript Trademark
In an open letter, JavaScript community leaders urge Oracle to give up the JavaScript trademark, arguing that it has been effectively abandoned through nonuse.
The zx package is a tool for writing better scripts in a Node.js environment. It provides a more convenient and modern way to write shell scripts using JavaScript, leveraging the power of Node.js and its ecosystem.
Running Shell Commands
This feature allows you to run shell commands directly from your JavaScript code using template literals. The `$` function is used to execute the command and handle the output.
const { $ } = require('zx');
(async () => {
await $`echo Hello, world!`;
})();
Handling Promises
zx makes it easy to handle promises and errors when running shell commands. You can use async/await syntax to manage asynchronous operations and catch errors using try/catch blocks.
const { $ } = require('zx');
(async () => {
try {
await $`exit 1`;
} catch (error) {
console.error('Command failed:', error);
}
})();
Using Environment Variables
You can set and use environment variables within your scripts. This is useful for configuring your script's behavior based on different environments or settings.
const { $ } = require('zx');
(async () => {
process.env.MY_VAR = 'Hello, world!';
await $`echo $MY_VAR`;
})();
File System Operations
zx provides convenient access to Node.js's fs module, allowing you to perform file system operations like reading and writing files with ease.
const { fs } = require('zx');
(async () => {
await fs.writeFile('example.txt', 'Hello, world!');
const content = await fs.readFile('example.txt', 'utf8');
console.log(content);
})();
ShellJS is a portable (Windows/Linux/macOS) implementation of Unix shell commands on top of the Node.js API. It provides a similar functionality to zx but uses a more traditional approach with a focus on compatibility with Unix shell commands.
Execa is a modern process execution library for Node.js. It provides a more powerful and flexible way to run shell commands compared to zx, with features like better error handling, streaming, and more detailed output.
The child_process module is a built-in Node.js module that provides the ability to spawn child processes. While it is more low-level and less convenient than zx, it offers more control and flexibility for advanced use cases.
#!/usr/bin/env zx
await $`cat package.json | grep name`
let 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`,
])
await $`ssh medv.io uptime`
Bash is great, but when it comes to writing scripts,
people usually choose a more convenient programming languages.
JavaScript is a perfect choose, but standard Node.js library
requires additional hassle before using. zx
package provides
useful wrappers around child_process
and gives sensible defaults.
npm i -g zx
Write your scripts in a file with .mjs
extension in order to
be able to use await
on top level. In you prefer .js
extension,
wrap your script in something like void async function () {...}()
.
Add next shebang at the beginning of your script:
#!/usr/bin/env zx
Now you will be able to run your script as:
chmod +x ./script.mjs
./script.mjs
Or via zx
bin:
zx ./script.mjs
Then using zx
bin or via shebang, all $
, cd
, fetch
, etc
available without imports.
$
Executes given string using exec
function
from child_process
package and returns Promise<ProcessOutput>
.
let count = parseInt(await $`ls -1 | wc -l`)
console.log(`Files count: ${count}`)
Example. Upload files in parallel:
let hosts = [...]
await Promise.all(hosts.map(host =>
$`rsync -azP ./src ${host}:/var/www`
))
class ProcessOutput {
readonly exitCode: number
readonly stdout: string
readonly stderr: string
toString(): string
}
If executed program returns non-zero exit code, ProcessOutput
will be thrown.
try {
await $`exit 1`
} catch (p) {
console.log(`Exit code: ${p.exitCode}`)
console.log(`Error: ${p.stderr}`)
}
cd
Changes working directory.
cd('/tmp')
await $`pwd` // outputs /tmp
test
Executes test
command using execSync
and returns true
or false
.
if (test('-f package.json')) {
console.log('Yes')
}
This is equivalent of next bash code:
if test -f package.json; then
echo Yes;
fi
fetch
This is a wrapper around node-fetch package.
let resp = await fetch('http://wttr.in')
if (resp.ok) {
console.log(await resp.text())
}
question
This is a wrapper around readline package.
type QuestionOptions = { choices: string[] }
function question(query: string, options?: QuestionOptions): Promise<string>
Usage:
let username = await question('What is your username? ')
let token = await question('Choose env variable: ', {
choices: Object.keys(process.env)
})
chalk
The chalk package available without importing inside scripts.
console.log(chalk.blue('Hello world!'))
fs
The fx package available without importing inside scripts.
let content = await fs.readFile('./package.json')
Promisified version imported by default. Same as if you write:
import {promises as fs} from 'fs'
os
The os package available without importing inside scripts.
await $`cd ${os.homedir()} && mkdir example`
$.shell
Specifies what shell is used. Default is /bin/sh
.
$.shell = '/bin/bash'
$.verbose
Specifies verbosity. Default: true
.
In verbose mode prints executed commands with outputs of it. Same as
set -x
in bash.
It's possible to use $
and others with explicit import.
#!/usr/bin/env node
import {$} from 'zx'
await $`date`
If arg to zx
bin starts with https://
, it will be downloaded and executed.
zx https://medv.io/example-script.mjs
Disclaimer: This is not an officially supported Google product.
FAQs
A tool for writing better scripts
The npm package zx receives a total of 526,257 weekly downloads. As such, zx popularity was classified as popular.
We found that zx demonstrated a healthy version release cadence and project activity because the last version was released less than a year ago. It has 2 open source maintainers collaborating on the project.
Did you know?
Socket for GitHub automatically highlights issues in each pull request and monitors the health of all your open source dependencies. Discover the contents of your packages and block harmful activity before you install or update your dependencies.
Security News
In an open letter, JavaScript community leaders urge Oracle to give up the JavaScript trademark, arguing that it has been effectively abandoned through nonuse.
Security News
The initial version of the Socket Python SDK is now on PyPI, enabling developers to more easily interact with the Socket REST API in Python projects.
Security News
Floating dependency ranges in npm can introduce instability and security risks into your project by allowing unverified or incompatible versions to be installed automatically, leading to unpredictable behavior and potential conflicts.