![require(esm) Backported to Node.js 20, Paving the Way for ESM-Only Packages](https://cdn.sanity.io/images/cgdhsj6q/production/be8ab80c8efa5907bc341c6fefe9aa20d239d890-1600x1097.png?w=400&fit=max&auto=format)
Security News
require(esm) Backported to Node.js 20, Paving the Way for ESM-Only Packages
require(esm) backported to Node.js 20, easing the transition to ESM-only packages and reducing complexity for developers as Node 18 nears end-of-life.
Execute shell commands from JavaScript.
@j-o-r/sh
is a Node.js module that simplifies the execution of shell commands within JavaScript applications. It provides a range of utilities to handle shell scripts and manage their output efficiently.
This project draws inspiration from the exceptional zx library. The core functionality of zx, particularly the shell execution method, has been extracted and forms the foundation of this project.
Install the module using npm:
npm install @j-o-r/sh
To execute a shell command, use the SH
function:
import { SH, cd, within, sleep, retry, expBackoff } from '@j-o-r/sh';
SH`your_shell_command`.run()
.then(output => {
console.log('Output:', output);
})
.catch(error => {
console.error('Error:', error);
});
const res = await SH`ls -FLa | grep package.json | wc -l`.run();
console.log(res);
const ar = within(async () => {
const res = await Promise.all([
SH`sleep 1; echo 1`.run(),
SH`sleep 2; echo 2`.run(),
sleep(2),
SH`sleep 3; echo 3`.run()
]);
});
const p = await retry(3, expBackoff(), () => SH`curl -s https://unreachable`.run());
The SH
method accepts a template literal string enclosed in backticks as its argument. It returns an SHDispatch
object.
The module also provides additional utilities for common tasks:
parseArgs(process.args)
: Transform an array of strings into an objectcd(dir)
: Change the working directory.sleep(duration)
: Pause execution for a specified duration.retry(count, interval, callback)
: Retry a command a specified number of times with an optional interval.readIn()
: Read from standard input.within(callback)
: Create an async context in a sync block.expBackoff(max, rand)
: Generate intervals for exponential backoff.jsType(any)
: Get the 'real' javascript variable typeassert.
: Node assert librarynew Test()
: A small sync/async minimal test frameworkThis class is returned by the SH
function. Here's a summary of its methods and properties:
SpawnSyncResponse
.Elementary usages, piped:
const res = await SH`ls -FLa | grep package.json | wc -l`.run();
console.log(res);
Feed command with content:
const res = await SH`wc -l`.run(`one\ntwo\n`);
console.log(res);
Create a command from a string
const command = "uname -r";
const content = await SH`${command}`.run();
console.log(content);
Async context with multiple commands and sleep:
within(async () => {
const res = await Promise.all([
SH`sleep 1; echo 1`.run(),
SH`sleep 2; echo 2`.run(),
sleep(2),
SH`sleep 3; echo 3`.run()
]);
console.log(res);
});
Retry with exponential backoff:
try {
const p = await retry(3, expBackoff(), () => SH`curl -s https://flipwrsi`.run());
} catch (e) {
console.error('Retry failed:', e);
}
Method for copying data to the clipboard:
/**
* Copy text to the clipboard
* @param {string} text
* @returns {Promise<string>}
*/
const copyToClipboard = async (text) => {
const prams = [
'-selection',
'clipboard'
]
return SH`xclip ${prams}`.options({stdio: 'inherit'}).run(text);
}
Open the 'vim' editor
SH`vim`.options({stdio: 'inherit'}).runSync();
Create and run a test
import { assert, jsType, Test} from '@j-o-r/sh';
const test = new Test();
test.add('Test is test in sync', () => {
assert.strictEqual(jsType(test), 'Test');
});
test.add('Test an Array in sync', () => {
assert.strictEqual(jsType([]), 'Array');
});
test.add('Test is test in async', async () => {
assert.strictEqual(jsType(test), 'Test');
});
test.add('Test is test in async, returning a promise', async () => {
return new Promise((resolve, _reject) => {
assert.strictEqual(jsType(test), 'Test');
resolve();
});
});
const report = await test.run();
if (report.errors > 0) {
process.exit(1);
}
// await test.run([0,3]); // only run test 0 and 3
This project is licensed under the Apache License, Version 2.0.
FAQs
Execute shell commands on Linux-based systems from javascript
The npm package @j-o-r/sh receives a total of 44 weekly downloads. As such, @j-o-r/sh popularity was classified as not popular.
We found that @j-o-r/sh demonstrated a healthy version release cadence and project activity because the last version was released less than a year ago. It has 1 open source maintainer 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
require(esm) backported to Node.js 20, easing the transition to ESM-only packages and reducing complexity for developers as Node 18 nears end-of-life.
Security News
PyPI now supports iOS and Android wheels, making it easier for Python developers to distribute mobile packages.
Security News
Create React App is officially deprecated due to React 19 issues and lack of maintenance—developers should switch to Vite or other modern alternatives.