├── .gitignore ├── .c8rc.json ├── .editorconfig ├── .github ├── SECURITY.md ├── dependabot.yml └── workflows │ ├── ci.yml │ └── npm-publish.yml ├── .prettierrc.json ├── vitest.config.ts ├── src ├── types │ └── cross-spawn.d.ts ├── non-zero-exit-error.ts ├── stream.ts ├── test │ ├── stream_test.ts │ ├── env_test.ts │ └── main_test.ts ├── env.ts └── main.ts ├── tsconfig.json ├── eslint.config.js ├── tsdown.config.ts ├── LICENSE ├── package.json └── README.md /.gitignore: -------------------------------------------------------------------------------- 1 | /.tshy 2 | /node_modules 3 | /lib 4 | /dist 5 | /coverage 6 | *.swp 7 | -------------------------------------------------------------------------------- /.c8rc.json: -------------------------------------------------------------------------------- 1 | { 2 | "reporter": ["lcov"], 3 | "exclude": [ 4 | "lib/test" 5 | ] 6 | } 7 | -------------------------------------------------------------------------------- /.editorconfig: -------------------------------------------------------------------------------- 1 | root = true 2 | 3 | [*] 4 | end_of_line = lf 5 | indent_size = 2 6 | indent_style = space 7 | trim_trailing_whitespace = true 8 | -------------------------------------------------------------------------------- /.github/SECURITY.md: -------------------------------------------------------------------------------- 1 | ## Security contact information 2 | 3 | To report a security vulnerability, please use the 4 | [Tidelift security contact](https://tidelift.com/security). 5 | Tidelift will coordinate the fix and disclosure. 6 | -------------------------------------------------------------------------------- /.prettierrc.json: -------------------------------------------------------------------------------- 1 | { 2 | "bracketSpacing": false, 3 | "printWidth": 80, 4 | "semi": true, 5 | "singleQuote": true, 6 | "tabWidth": 2, 7 | "trailingComma": "none", 8 | "useTabs": false, 9 | "arrowParens": "always" 10 | } 11 | -------------------------------------------------------------------------------- /vitest.config.ts: -------------------------------------------------------------------------------- 1 | import { defineConfig } from 'vitest/config' 2 | 3 | export default defineConfig({ 4 | test: { 5 | coverage: { 6 | provider: 'v8' 7 | }, 8 | include: [ 9 | 'src/**/*_test.ts' 10 | ] 11 | } 12 | }) 13 | -------------------------------------------------------------------------------- /src/types/cross-spawn.d.ts: -------------------------------------------------------------------------------- 1 | import type {SpawnOptions} from 'child_process'; 2 | 3 | declare module 'cross-spawn' { 4 | export function _parse( 5 | file: string, 6 | args: string[], 7 | options?: SpawnOptions 8 | ): {command: string; args: string[]; options: SpawnOptions}; 9 | } 10 | -------------------------------------------------------------------------------- /tsconfig.json: -------------------------------------------------------------------------------- 1 | { 2 | "compilerOptions": { 3 | "target": "es2022", 4 | "module": "node16", 5 | "moduleResolution": "node16", 6 | "types": ["node"], 7 | "declaration": true, 8 | "outDir": "./lib", 9 | "importHelpers": false, 10 | "isolatedModules": true, 11 | "forceConsistentCasingInFileNames": true, 12 | "strict": true, 13 | "noUnusedLocals": true, 14 | "noUnusedParameters": true 15 | }, 16 | "include": [ 17 | "src/**/*.ts", 18 | "src/types/*.d.ts" 19 | ] 20 | } 21 | -------------------------------------------------------------------------------- /src/non-zero-exit-error.ts: -------------------------------------------------------------------------------- 1 | import type {Result, Output} from './main.js'; 2 | 3 | export class NonZeroExitError extends Error { 4 | public readonly result: Result; 5 | public readonly output?: Output; 6 | 7 | public get exitCode(): number | undefined { 8 | if (this.result.exitCode !== null) { 9 | return this.result.exitCode; 10 | } 11 | return undefined; 12 | } 13 | 14 | public constructor(result: Result, output?: Output) { 15 | super(`Process exited with non-zero status (${result.exitCode})`); 16 | 17 | this.result = result; 18 | this.output = output; 19 | } 20 | } 21 | -------------------------------------------------------------------------------- /.github/dependabot.yml: -------------------------------------------------------------------------------- 1 | version: 2 2 | updates: 3 | - package-ecosystem: npm 4 | directory: '/' 5 | schedule: 6 | interval: weekly 7 | open-pull-requests-limit: 10 8 | versioning-strategy: increase 9 | groups: 10 | production-dependencies: 11 | dependency-type: "production" 12 | development-dependencies: 13 | dependency-type: "development" 14 | - package-ecosystem: 'github-actions' 15 | directory: '/' 16 | schedule: 17 | interval: weekly 18 | groups: 19 | github-actions: 20 | patterns: 21 | - "*" 22 | -------------------------------------------------------------------------------- /eslint.config.js: -------------------------------------------------------------------------------- 1 | import eslint from '@eslint/js'; 2 | import {configs as tseslintConfigs} from 'typescript-eslint'; 3 | 4 | const {configs: eslintConfigs} = eslint; 5 | 6 | export default [ 7 | { 8 | files: [ 9 | 'src/**/*.ts' 10 | ] 11 | }, 12 | eslintConfigs.recommended, 13 | ...tseslintConfigs.strict, 14 | { 15 | rules: { 16 | '@typescript-eslint/no-unused-vars': 'off' 17 | } 18 | }, 19 | { 20 | files: [ 21 | 'src/test/**/*.ts' 22 | ], 23 | rules: { 24 | '@typescript-eslint/no-dynamic-delete': 'off', 25 | '@typescript-eslint/no-non-null-assertion': 'off', 26 | '@typescript-eslint/no-unused-expressions': 'off' 27 | } 28 | } 29 | ]; 30 | -------------------------------------------------------------------------------- /src/stream.ts: -------------------------------------------------------------------------------- 1 | import {type EventEmitter} from 'node:events'; 2 | import {type Readable, PassThrough} from 'node:stream'; 3 | 4 | export const waitForEvent = ( 5 | emitter: EventEmitter, 6 | name: string 7 | ): Promise => { 8 | return new Promise((resolve) => { 9 | emitter.on(name, resolve); 10 | }); 11 | }; 12 | 13 | export const combineStreams = (streams: Readable[]): Readable => { 14 | let streamCount = streams.length; 15 | const combined = new PassThrough(); 16 | const maybeEmitEnd = () => { 17 | if (--streamCount === 0) { 18 | combined.emit('end'); 19 | } 20 | }; 21 | 22 | for (const stream of streams) { 23 | stream.pipe(combined, {end: false}); 24 | stream.on('end', maybeEmitEnd); 25 | } 26 | 27 | return combined; 28 | }; 29 | -------------------------------------------------------------------------------- /tsdown.config.ts: -------------------------------------------------------------------------------- 1 | import {defineConfig} from 'tsdown'; 2 | import licenses from 'rollup-plugin-license'; 3 | 4 | export default defineConfig({ 5 | entry: 'src/main.ts', 6 | target: 'es2022', 7 | clean: true, 8 | dts: true, 9 | plugins: [ 10 | licenses({ 11 | thirdParty: { 12 | output: { 13 | file: 'dist/LICENSES.txt', 14 | template(dependencies) { 15 | return dependencies.map((dependency) => 16 | `${dependency.name}:${dependency.version} -- ${dependency.licenseText}` 17 | ).join('\n'); 18 | } 19 | } 20 | } 21 | }) as never 22 | ], 23 | outputOptions: { 24 | minify: { 25 | mangle: true, 26 | compress: false, 27 | removeWhitespace: false 28 | } 29 | } 30 | }); 31 | -------------------------------------------------------------------------------- /LICENSE: -------------------------------------------------------------------------------- 1 | MIT License 2 | 3 | Copyright (c) 2024 Tinylibs 4 | 5 | Permission is hereby granted, free of charge, to any person obtaining a copy 6 | of this software and associated documentation files (the "Software"), to deal 7 | in the Software without restriction, including without limitation the rights 8 | to use, copy, modify, merge, publish, distribute, sublicense, and/or sell 9 | copies of the Software, and to permit persons to whom the Software is 10 | furnished to do so, subject to the following conditions: 11 | 12 | The above copyright notice and this permission notice shall be included in all 13 | copies or substantial portions of the Software. 14 | 15 | THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR 16 | IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, 17 | FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE 18 | AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER 19 | LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, 20 | OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE 21 | SOFTWARE. 22 | -------------------------------------------------------------------------------- /.github/workflows/ci.yml: -------------------------------------------------------------------------------- 1 | name: CI Build 2 | 3 | on: 4 | push: 5 | branches: main 6 | pull_request: 7 | branches: main 8 | 9 | jobs: 10 | lint: 11 | runs-on: ubuntu-latest 12 | 13 | steps: 14 | - uses: actions/checkout@8e8c483db84b4bee98b60c0593521ed34d9990e8 # v6.0.1 15 | - uses: actions/setup-node@395ad3262231945c25e8478fd5baf05154b1d79f # v6.1.0 16 | with: 17 | node-version: latest 18 | - run: npm ci 19 | - run: npm run format:check 20 | - run: npm run lint 21 | build: 22 | name: Build ${{ matrix.node-version }} @ ${{ matrix.os }} 23 | 24 | strategy: 25 | matrix: 26 | node-version: 27 | - 18 28 | - 20 29 | - latest 30 | os: [ubuntu-latest, windows-latest] 31 | 32 | runs-on: ${{ matrix.os }} 33 | 34 | steps: 35 | - uses: actions/checkout@8e8c483db84b4bee98b60c0593521ed34d9990e8 # v6.0.1 36 | - name: Use Node.js ${{ matrix.node-version }} 37 | uses: actions/setup-node@395ad3262231945c25e8478fd5baf05154b1d79f # v6.1.0 38 | with: 39 | node-version: ${{ matrix.node-version }} 40 | - run: npm ci 41 | - run: npm run test 42 | -------------------------------------------------------------------------------- /.github/workflows/npm-publish.yml: -------------------------------------------------------------------------------- 1 | name: Publish 2 | 3 | on: 4 | release: 5 | types: [published] 6 | 7 | jobs: 8 | build: 9 | runs-on: ubuntu-latest 10 | steps: 11 | - uses: actions/checkout@8e8c483db84b4bee98b60c0593521ed34d9990e8 # v6.0.1 12 | - uses: actions/setup-node@395ad3262231945c25e8478fd5baf05154b1d79f # v6.1.0 13 | with: 14 | node-version: 22 15 | - run: npm ci 16 | - run: npm run lint 17 | - run: npm test 18 | 19 | publish-npm: 20 | needs: build 21 | runs-on: ubuntu-latest 22 | permissions: 23 | id-token: write 24 | contents: read 25 | steps: 26 | - uses: actions/checkout@8e8c483db84b4bee98b60c0593521ed34d9990e8 # v6.0.1 27 | - uses: actions/setup-node@395ad3262231945c25e8478fd5baf05154b1d79f # v6.1.0 28 | with: 29 | node-version: 22.x 30 | registry-url: 'https://registry.npmjs.org' 31 | cache: 'npm' 32 | - run: npm install -g npm@latest 33 | - run: npm ci 34 | - run: npm version ${TAG_NAME} --git-tag-version=false 35 | env: 36 | TAG_NAME: ${{ github.ref_name }} 37 | - run: npm publish --access public --tag next 38 | if: github.event.release.prerelease 39 | - run: npm publish --access public 40 | if: "!github.event.release.prerelease" 41 | -------------------------------------------------------------------------------- /src/test/stream_test.ts: -------------------------------------------------------------------------------- 1 | import {combineStreams, waitForEvent} from '../stream.js'; 2 | import {describe, test, expect} from 'vitest'; 3 | import {EventEmitter} from 'node:events'; 4 | import {Readable} from 'node:stream'; 5 | 6 | describe('waitForEvent', async () => { 7 | test('waits for event to fire', async () => { 8 | const emitter = new EventEmitter(); 9 | const waiter = waitForEvent(emitter, 'foo'); 10 | emitter.emit('foo'); 11 | await waiter; 12 | }); 13 | }); 14 | 15 | describe('combineStreams', async () => { 16 | test('works with a single stream', async () => { 17 | const stream = Readable.from(['foo', 'bar']); 18 | const combined = combineStreams([stream]); 19 | const chunks: string[] = []; 20 | combined.on('data', (chunk: Buffer) => { 21 | chunks.push(chunk.toString()); 22 | }); 23 | await waitForEvent(combined, 'end'); 24 | expect(chunks).toEqual(['foo', 'bar']); 25 | }); 26 | 27 | test('works with multiple streams', async () => { 28 | const stream0 = Readable.from(['foo']); 29 | const stream1 = Readable.from(['bar', 'baz']); 30 | const combined = combineStreams([stream0, stream1]); 31 | const chunks: string[] = []; 32 | combined.on('data', (chunk: Buffer) => { 33 | chunks.push(chunk.toString()); 34 | }); 35 | await waitForEvent(combined, 'end'); 36 | expect(chunks).toEqual(['foo', 'bar', 'baz']); 37 | }); 38 | }); 39 | -------------------------------------------------------------------------------- /src/env.ts: -------------------------------------------------------------------------------- 1 | import { 2 | delimiter as pathDelimiter, 3 | resolve as resolvePath, 4 | dirname 5 | } from 'node:path'; 6 | 7 | export type EnvLike = (typeof process)['env']; 8 | 9 | export interface EnvPathInfo { 10 | key: string; 11 | value: string; 12 | } 13 | 14 | const isPathLikePattern = /^path$/i; 15 | const defaultEnvPathInfo = {key: 'PATH', value: ''}; 16 | 17 | export function getPathFromEnv(env: EnvLike): EnvPathInfo { 18 | for (const key in env) { 19 | if ( 20 | !Object.prototype.hasOwnProperty.call(env, key) || 21 | !isPathLikePattern.test(key) 22 | ) { 23 | continue; 24 | } 25 | 26 | const value = env[key]; 27 | 28 | if (!value) { 29 | return defaultEnvPathInfo; 30 | } 31 | 32 | return {key, value}; 33 | } 34 | return defaultEnvPathInfo; 35 | } 36 | 37 | function addNodeBinToPath(cwd: string, path: EnvPathInfo): EnvPathInfo { 38 | const parts = path.value.split(pathDelimiter); 39 | 40 | let currentPath = cwd; 41 | let lastPath: string; 42 | 43 | do { 44 | parts.push(resolvePath(currentPath, 'node_modules', '.bin')); 45 | lastPath = currentPath; 46 | currentPath = dirname(currentPath); 47 | } while (currentPath !== lastPath); 48 | 49 | return {key: path.key, value: parts.join(pathDelimiter)}; 50 | } 51 | 52 | export function computeEnv(cwd: string, env?: EnvLike): EnvLike { 53 | const envWithDefault = { 54 | ...process.env, 55 | ...env 56 | }; 57 | const envPathInfo = addNodeBinToPath(cwd, getPathFromEnv(envWithDefault)); 58 | envWithDefault[envPathInfo.key] = envPathInfo.value; 59 | 60 | return envWithDefault; 61 | } 62 | -------------------------------------------------------------------------------- /package.json: -------------------------------------------------------------------------------- 1 | { 2 | "name": "tinyexec", 3 | "version": "0.0.0-dev", 4 | "type": "module", 5 | "description": "A minimal library for executing processes in Node", 6 | "main": "./dist/main.js", 7 | "engines": { 8 | "node": ">=18" 9 | }, 10 | "files": [ 11 | "dist" 12 | ], 13 | "scripts": { 14 | "build": "tsdown", 15 | "build:types": "tsc", 16 | "dev": "tsdown --watch", 17 | "format": "prettier --write src", 18 | "format:check": "prettier --check src", 19 | "lint": "eslint src", 20 | "prepare": "npm run build", 21 | "test": "npm run build && vitest run" 22 | }, 23 | "repository": { 24 | "type": "git", 25 | "url": "git+https://github.com/tinylibs/tinyexec.git" 26 | }, 27 | "keywords": [ 28 | "execa", 29 | "exec", 30 | "tiny", 31 | "child_process", 32 | "spawn" 33 | ], 34 | "author": "James Garbutt (https://github.com/43081j)", 35 | "license": "MIT", 36 | "bugs": { 37 | "url": "https://github.com/tinylibs/tinyexec/issues" 38 | }, 39 | "homepage": "https://github.com/tinylibs/tinyexec#readme", 40 | "devDependencies": { 41 | "@eslint/js": "^9.39.1", 42 | "@types/cross-spawn": "^6.0.6", 43 | "@types/node": "^24.10.0", 44 | "@vitest/coverage-v8": "^4.0.7", 45 | "cross-spawn": "^7.0.6", 46 | "eslint": "^9.39.1", 47 | "prettier": "^3.6.2", 48 | "rollup-plugin-license": "^3.6.0", 49 | "tsdown": "^0.9.9", 50 | "typescript": "^5.9.3", 51 | "typescript-eslint": "^8.46.3", 52 | "vitest": "^4.0.7" 53 | }, 54 | "exports": { 55 | ".": { 56 | "types": "./dist/main.d.ts", 57 | "default": "./dist/main.js" 58 | }, 59 | "./package.json": "./package.json" 60 | }, 61 | "types": "./dist/main.d.ts" 62 | } 63 | -------------------------------------------------------------------------------- /src/test/env_test.ts: -------------------------------------------------------------------------------- 1 | import {computeEnv, getPathFromEnv} from '../env.js'; 2 | import {expect, test, describe} from 'vitest'; 3 | import process from 'node:process'; 4 | import {sep as pathSep} from 'node:path'; 5 | 6 | const pathKey = getPathFromEnv(process.env).key; 7 | 8 | describe('computeEnv', async () => { 9 | test('adds node binaries to path', () => { 10 | const env = computeEnv(process.cwd()); 11 | const path = env[pathKey]!; 12 | 13 | expect(path.includes(`node_modules${pathSep}.bin`)).ok; 14 | }); 15 | 16 | test('extends process env', () => { 17 | const env = computeEnv(process.cwd(), { 18 | foo: 'bar' 19 | }); 20 | 21 | for (const key in process.env) { 22 | if (key.toUpperCase() !== 'PATH') { 23 | expect(env[key]).toBe(process.env[key]); 24 | } 25 | } 26 | 27 | expect(env.foo).toBe('bar'); 28 | }); 29 | 30 | test('supports case-insensitive path keys', () => { 31 | const originalPath = process.env[pathKey]; 32 | try { 33 | delete process.env[pathKey]; 34 | const env = computeEnv(process.cwd(), { 35 | PatH: '/' 36 | }); 37 | const keys = [...Object.keys(env)]; 38 | 39 | expect(keys.includes('PatH')).ok; 40 | expect(!keys.includes(pathKey)).ok; 41 | } finally { 42 | process.env[pathKey] = originalPath; 43 | } 44 | }); 45 | 46 | test('uses default key if empty path found', () => { 47 | const originalPath = process.env[pathKey]; 48 | try { 49 | delete process.env[pathKey]; 50 | const env = computeEnv(process.cwd(), { 51 | PatH: undefined 52 | }); 53 | 54 | expect(typeof env['PATH'] === 'string').ok; 55 | expect(env['PatH']).toBe(undefined); 56 | } finally { 57 | process.env[pathKey] = originalPath; 58 | } 59 | }); 60 | 61 | test('uses default key if no path found', () => { 62 | const originalPath = process.env[pathKey]; 63 | try { 64 | delete process.env[pathKey]; 65 | const env = computeEnv(process.cwd()); 66 | 67 | expect(typeof env['PATH'] === 'string').ok; 68 | } finally { 69 | process.env[pathKey] = originalPath; 70 | } 71 | }); 72 | }); 73 | -------------------------------------------------------------------------------- /src/test/main_test.ts: -------------------------------------------------------------------------------- 1 | import {x, NonZeroExitError} from '../main.js'; 2 | import {describe, test, expect} from 'vitest'; 3 | import os from 'node:os'; 4 | 5 | const isWindows = os.platform() === 'win32'; 6 | 7 | describe('exec', async () => { 8 | test('pid is number', async () => { 9 | const proc = x('echo', ['foo']); 10 | await proc; 11 | expect(typeof proc.pid === 'number').ok; 12 | }); 13 | 14 | test('exitCode is set correctly', async () => { 15 | const proc = x('echo', ['foo']); 16 | expect(proc.exitCode).toBe(undefined); 17 | const result = await proc; 18 | expect(proc.exitCode).toBe(0); 19 | expect(result.exitCode).toBe(0); 20 | }); 21 | 22 | test('non-zero exitCode throws when throwOnError=true', async () => { 23 | const proc = x('node', ['-e', 'process.exit(1);'], {throwOnError: true}); 24 | await expect(async () => { 25 | await proc; 26 | }).rejects.toThrow(NonZeroExitError); 27 | expect(proc.exitCode).toBe(1); 28 | }); 29 | 30 | test('async iterator gets correct output', async () => { 31 | const proc = x('node', ['-e', "console.log('foo'); console.log('bar');"]); 32 | const lines = []; 33 | for await (const line of proc) { 34 | lines.push(line); 35 | } 36 | 37 | expect(lines).toEqual(['foo', 'bar']); 38 | }); 39 | 40 | test('resolves to stdout', async () => { 41 | const result = await x('node', ['-e', "console.log('foo')"]); 42 | expect(result.stdout).toBe('foo\n'); 43 | expect(result.stderr).toBe(''); 44 | }); 45 | 46 | test('captures stderr', async () => { 47 | const result = await x('node', ['-e', "console.error('some error')"]); 48 | expect(result.stderr).toBe('some error\n'); 49 | expect(result.stdout).toBe(''); 50 | }); 51 | }); 52 | 53 | if (isWindows) { 54 | describe('exec (windows)', async () => { 55 | test('times out after defined timeout (ms)', async () => { 56 | // Somewhat filthy way of waiting for 2 seconds across cmd/ps 57 | const proc = x('ping', ['127.0.0.1', '-n', '2'], {timeout: 100}); 58 | await expect(async () => { 59 | await proc; 60 | }).rejects.toThrow(); 61 | expect(proc.killed).toBe(true); 62 | expect(proc.process!.signalCode).toBe('SIGTERM'); 63 | }); 64 | 65 | test('does not throw spawn errors', async () => { 66 | const result = await x('definitelyNonExistent'); 67 | expect(result.stderr).toBe( 68 | "'definitelyNonExistent' is not recognized as an internal" + 69 | ' or external command,\r\noperable program or batch file.\r\n' 70 | ); 71 | expect(result.stdout).toBe(''); 72 | }); 73 | 74 | test('throws spawn errors when throwOnError=true', async () => { 75 | const proc = x('definitelyNonExistent', [], {throwOnError: true}); 76 | try { 77 | await proc; 78 | expect.fail('Expected to throw'); 79 | } catch (err) { 80 | expect(err instanceof NonZeroExitError).ok; 81 | expect((err as NonZeroExitError).output?.stderr).toBe( 82 | "'definitelyNonExistent' is not recognized as an internal" + 83 | ' or external command,\r\noperable program or batch file.\r\n' 84 | ); 85 | expect((err as NonZeroExitError).output?.stdout).toBe(''); 86 | } 87 | }); 88 | 89 | test('kill terminates the process', async () => { 90 | // Somewhat filthy way of waiting for 2 seconds across cmd/ps 91 | const proc = x('ping', ['127.0.0.1', '-n', '2']); 92 | const result = proc.kill(); 93 | expect(result).ok; 94 | expect(proc.killed).ok; 95 | expect(proc.aborted).toBe(false); 96 | }); 97 | 98 | test('pipe correctly pipes output', async () => { 99 | const echoProc = x('node', ['-e', "console.log('foo')"]); 100 | const grepProc = echoProc.pipe('findstr', ['f']); 101 | const result = await grepProc; 102 | 103 | expect(result.stderr).toBe(''); 104 | expect(result.stdout).toBe('foo\n'); 105 | expect(result.exitCode).toBe(0); 106 | expect(echoProc.exitCode).toBe(0); 107 | expect(grepProc.exitCode).toBe(0); 108 | }); 109 | 110 | test('signal can be used to abort execution', async () => { 111 | const controller = new AbortController(); 112 | // Somewhat filthy way of waiting for 2 seconds across cmd/ps 113 | const proc = x('ping', ['127.0.0.1', '-n', '2'], { 114 | signal: controller.signal 115 | }); 116 | controller.abort(); 117 | const result = await proc; 118 | expect(proc.aborted).ok; 119 | expect(proc.killed).ok; 120 | expect(result.stderr).toBe(''); 121 | expect(result.stdout).toBe(''); 122 | }); 123 | 124 | test('async iterator receives errors as lines', async () => { 125 | const proc = x('nonexistentforsure'); 126 | const lines: string[] = []; 127 | for await (const line of proc) { 128 | lines.push(line); 129 | } 130 | 131 | expect(lines).toEqual([ 132 | "'nonexistentforsure' is not recognized as an internal or " + 133 | 'external command,', 134 | 'operable program or batch file.' 135 | ]); 136 | }); 137 | }); 138 | } 139 | 140 | if (!isWindows) { 141 | describe('exec (unix-like)', async () => { 142 | test('times out after defined timeout (ms)', async () => { 143 | const proc = x('sleep', ['0.2'], {timeout: 100}); 144 | await expect(async () => { 145 | await proc; 146 | }).rejects.toThrow(); 147 | expect(proc.killed).toBe(true); 148 | expect(proc.process!.signalCode).toBe('SIGTERM'); 149 | }); 150 | 151 | test('throws spawn errors', async () => { 152 | const proc = x('definitelyNonExistent'); 153 | await expect(async () => { 154 | await proc; 155 | }).rejects.toThrow('spawn definitelyNonExistent ENOENT'); 156 | }); 157 | 158 | test('kill terminates the process', async () => { 159 | const proc = x('sleep', ['5']); 160 | const result = proc.kill(); 161 | expect(result).ok; 162 | expect(proc.killed).ok; 163 | expect(proc.aborted).toBe(false); 164 | }); 165 | 166 | test('pipe correctly pipes output', async () => { 167 | const echoProc = x('echo', ['foo\nbar']); 168 | const grepProc = echoProc.pipe('grep', ['foo']); 169 | const result = await grepProc; 170 | 171 | expect(result.stderr).toBe(''); 172 | expect(result.stdout).toBe('foo\n'); 173 | expect(result.exitCode).toBe(0); 174 | expect(echoProc.exitCode).toBe(0); 175 | expect(grepProc.exitCode).toBe(0); 176 | }); 177 | 178 | test('signal can be used to abort execution', async () => { 179 | const controller = new AbortController(); 180 | const proc = x('sleep', ['4'], {signal: controller.signal}); 181 | controller.abort(); 182 | const result = await proc; 183 | expect(proc.aborted).ok; 184 | expect(proc.killed).ok; 185 | expect(result.stderr).toBe(''); 186 | expect(result.stdout).toBe(''); 187 | }); 188 | 189 | test('async iterator receives errors', async () => { 190 | const proc = x('nonexistentforsure'); 191 | await expect(async () => { 192 | for await (const line of proc) { 193 | line; 194 | } 195 | }).rejects.toThrow(); 196 | }); 197 | }); 198 | } 199 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | # tinyexec 📟 2 | 3 | > A minimal package for executing commands 4 | 5 | This package was created to provide a minimal way of interacting with child 6 | processes without having to manually deal with streams, piping, etc. 7 | 8 | ## Installing 9 | 10 | ```sh 11 | $ npm i -S tinyexec 12 | ``` 13 | 14 | ## Usage 15 | 16 | A process can be spawned and awaited like so: 17 | 18 | ```ts 19 | import {x} from 'tinyexec'; 20 | 21 | const result = await x('ls', ['-l']); 22 | 23 | // result.stdout - the stdout as a string 24 | // result.stderr - the stderr as a string 25 | // result.exitCode - the process exit code as a number 26 | ``` 27 | 28 | By default, tinyexec does not throw on non‑zero exit codes. Check `result.exitCode` or pass `{throwOnError: true}`. 29 | 30 | Output is returned exactly as produced; trailing newlines are not trimmed. If you need trimming, do it explicitly: 31 | 32 | ```ts 33 | const clean = result.stdout.replace(/\r?\n$/, ''); 34 | ``` 35 | 36 | You may also iterate over the lines of output via an async loop: 37 | 38 | ```ts 39 | import {x} from 'tinyexec'; 40 | 41 | const proc = x('ls', ['-l']); 42 | 43 | for await (const line of proc) { 44 | // line will be from stderr/stdout in the order you'd see it in a term 45 | } 46 | ``` 47 | 48 | ### Options 49 | 50 | Options can be passed to have finer control over spawning of the process: 51 | 52 | ```ts 53 | await x('ls', [], { 54 | timeout: 1000 55 | }); 56 | ``` 57 | 58 | The options object can have the following properties: 59 | 60 | - `signal` - an `AbortSignal` to allow aborting of the execution 61 | - `timeout` - time in milliseconds at which the process will be forceably killed 62 | - `persist` - if `true`, the process will continue after the host exits 63 | - `stdin` - another `Result` can be used as the input to this process 64 | - `nodeOptions` - any valid options to node's underlying `spawn` function 65 | - `throwOnError` - if true, non-zero exit codes will throw an error 66 | 67 | ### Piping to another process 68 | 69 | You can pipe a process to another via the `pipe` method: 70 | 71 | ```ts 72 | const proc1 = x('ls', ['-l']); 73 | const proc2 = proc1.pipe('grep', ['.js']); 74 | const result = await proc2; 75 | 76 | console.log(result.stdout); 77 | ``` 78 | 79 | `pipe` takes the same options as a regular execution. For example, you can 80 | pass a timeout to the pipe call: 81 | 82 | ```ts 83 | proc1.pipe('grep', ['.js'], { 84 | timeout: 2000 85 | }); 86 | ``` 87 | 88 | ### Killing a process 89 | 90 | You can kill the process via the `kill` method: 91 | 92 | ```ts 93 | const proc = x('ls'); 94 | 95 | proc.kill(); 96 | 97 | // or with a signal 98 | proc.kill('SIGHUP'); 99 | ``` 100 | 101 | ### Node modules/binaries 102 | 103 | By default, node's available binaries from `node_modules` will be accessible 104 | in your command. 105 | 106 | For example, in a repo which has `eslint` installed: 107 | 108 | ```ts 109 | await x('eslint', ['.']); 110 | ``` 111 | 112 | In this example, `eslint` will come from the locally installed `node_modules`. 113 | 114 | ### Using an abort signal 115 | 116 | An abort signal can be passed to a process in order to abort it at a later 117 | time. This will result in the process being killed and `aborted` being set 118 | to `true`. 119 | 120 | ```ts 121 | const aborter = new AbortController(); 122 | const proc = x('node', ['./foo.mjs'], { 123 | signal: aborter.signal 124 | }); 125 | 126 | // elsewhere... 127 | aborter.abort(); 128 | 129 | await proc; 130 | 131 | proc.aborted; // true 132 | proc.killed; // true 133 | ``` 134 | 135 | ### Using with command strings 136 | 137 | If you need to continue supporting commands as strings (e.g. "command arg0 arg1"), 138 | you can use [args-tokenizer](https://github.com/TrySound/args-tokenizer), 139 | a lightweight library for parsing shell command strings into an array. 140 | 141 | ```ts 142 | import {x} from 'tinyexec'; 143 | import {tokenizeArgs} from 'args-tokenizer'; 144 | 145 | const commandString = 'echo "Hello, World!"'; 146 | const [command, ...args] = tokenizeArgs(commandString); 147 | const result = await x(command, args); 148 | 149 | result.stdout; // Hello, World! 150 | ``` 151 | 152 | ## API 153 | 154 | Calling `x(command[, args])` returns an awaitable `Result` which has the 155 | following API methods and properties available: 156 | 157 | ### `pipe(command[, args[, options]])` 158 | 159 | Pipes the current command to another. For example: 160 | 161 | ```ts 162 | x('ls', ['-l']) 163 | .pipe('grep', ['js']); 164 | ``` 165 | 166 | The parameters are as follows: 167 | 168 | - `command` - the command to execute (_without any arguments_) 169 | - `args` - an array of arguments 170 | - `options` - options object 171 | 172 | ### `process` 173 | 174 | The underlying Node.js `ChildProcess`. tinyexec keeps the surface minimal and does not re‑expose every child_process method/event. Use `proc.process` for advanced access (streams, events, etc.). 175 | 176 | ```ts 177 | const proc = x('node', ['./foo.mjs']); 178 | 179 | proc.process?.stdout?.on('data', (chunk) => { 180 | // ... 181 | }); 182 | proc.process?.once('close', (code) => { 183 | // ... 184 | }); 185 | ``` 186 | 187 | ### `kill([signal])` 188 | 189 | Kills the current process with the specified signal. By default, this will 190 | use the `SIGTERM` signal. 191 | 192 | For example: 193 | 194 | ```ts 195 | const proc = x('ls'); 196 | 197 | proc.kill(); 198 | ``` 199 | 200 | ### `pid` 201 | 202 | The current process ID. For example: 203 | 204 | ```ts 205 | const proc = x('ls'); 206 | 207 | proc.pid; // number 208 | ``` 209 | 210 | ### `aborted` 211 | 212 | Whether the process has been aborted or not (via the `signal` originally 213 | passed in the options object). 214 | 215 | For example: 216 | 217 | ```ts 218 | const proc = x('ls'); 219 | 220 | proc.aborted; // bool 221 | ``` 222 | 223 | ### `killed` 224 | 225 | Whether the process has been killed or not (e.g. via `kill()` or an abort 226 | signal). 227 | 228 | For example: 229 | 230 | ```ts 231 | const proc = x('ls'); 232 | 233 | proc.killed; // bool 234 | ``` 235 | 236 | ### `exitCode` 237 | 238 | The exit code received when the process completed execution. 239 | 240 | For example: 241 | 242 | ```ts 243 | const proc = x('ls'); 244 | 245 | proc.exitCode; // number (e.g. 1) 246 | ``` 247 | 248 | ## Comparison with other libraries 249 | 250 | `tinyexec` aims to provide a lightweight layer on top of Node's own 251 | `child_process` API. 252 | 253 | Some clear benefits compared to other libraries are that `tinyexec` will be much lighter, have a much 254 | smaller footprint and will have a less abstract interface (less "magic"). It 255 | will also have equal security and cross-platform support to popular 256 | alternatives. 257 | 258 | There are various features other libraries include which we are unlikely 259 | to ever implement, as they would prevent us from providing a lightweight layer. 260 | 261 | For example, if you'd like write scripts rather than individual commands, and 262 | prefer to use templating, we'd definitely recommend 263 | [zx](https://github.com/google/zx). zx is a much higher level library which 264 | does some of the same work `tinyexec` does but behind a template string 265 | interface. 266 | 267 | Similarly, libraries like `execa` will provide helpers for various things 268 | like passing files as input to processes. We opt not to support features like 269 | this since many of them are easy to do yourself (using Node's own APIs). 270 | -------------------------------------------------------------------------------- /src/main.ts: -------------------------------------------------------------------------------- 1 | import {type ChildProcess, type SpawnOptions, spawn} from 'node:child_process'; 2 | import {type Readable} from 'node:stream'; 3 | import {normalize as normalizePath} from 'node:path'; 4 | import {cwd as getCwd} from 'node:process'; 5 | import {computeEnv} from './env.js'; 6 | import {combineStreams} from './stream.js'; 7 | import readline from 'node:readline'; 8 | import {_parse} from 'cross-spawn'; 9 | import {NonZeroExitError} from './non-zero-exit-error.js'; 10 | 11 | export {NonZeroExitError}; 12 | 13 | export interface Output { 14 | stderr: string; 15 | stdout: string; 16 | exitCode: number | undefined; 17 | } 18 | 19 | // eslint-disable-next-line @typescript-eslint/no-empty-object-type 20 | export interface PipeOptions extends Options {} 21 | 22 | export type KillSignal = Parameters[0]; 23 | 24 | export interface OutputApi extends AsyncIterable { 25 | pipe( 26 | command: string, 27 | args?: string[], 28 | options?: Partial 29 | ): Result; 30 | process: ChildProcess | undefined; 31 | kill(signal?: KillSignal): boolean; 32 | 33 | // Getters 34 | get pid(): number | undefined; 35 | get aborted(): boolean; 36 | get killed(): boolean; 37 | get exitCode(): number | undefined; 38 | } 39 | 40 | export type Result = PromiseLike & OutputApi; 41 | 42 | export interface Options { 43 | signal: AbortSignal; 44 | nodeOptions: SpawnOptions; 45 | timeout: number; 46 | persist: boolean; 47 | stdin: ExecProcess; 48 | throwOnError: boolean; 49 | } 50 | 51 | export interface TinyExec { 52 | (command: string, args?: string[], options?: Partial): Result; 53 | } 54 | 55 | const defaultOptions: Partial = { 56 | timeout: undefined, 57 | persist: false 58 | }; 59 | 60 | const defaultNodeOptions: SpawnOptions = { 61 | windowsHide: true 62 | }; 63 | 64 | function normaliseCommandAndArgs( 65 | command: string, 66 | args?: string[] 67 | ): { 68 | command: string; 69 | args: string[]; 70 | } { 71 | const normalisedPath = normalizePath(command); 72 | const normalisedArgs = args ?? []; 73 | 74 | return { 75 | command: normalisedPath, 76 | args: normalisedArgs 77 | }; 78 | } 79 | 80 | function combineSignals(signals: Iterable): AbortSignal { 81 | const controller = new AbortController(); 82 | 83 | for (const signal of signals) { 84 | if (signal.aborted) { 85 | controller.abort(); 86 | return signal; 87 | } 88 | 89 | const onAbort = (): void => { 90 | controller.abort(signal.reason); 91 | }; 92 | signal.addEventListener('abort', onAbort, { 93 | signal: controller.signal 94 | }); 95 | } 96 | 97 | return controller.signal; 98 | } 99 | 100 | async function readStream(stream: Readable): Promise { 101 | let output = ''; 102 | for await (const chunk of stream) { 103 | output += chunk.toString(); 104 | } 105 | return output; 106 | } 107 | 108 | export class ExecProcess implements Result { 109 | protected _process?: ChildProcess; 110 | protected _aborted: boolean = false; 111 | protected _options: Partial; 112 | protected _command: string; 113 | protected _args: string[]; 114 | protected _resolveClose?: () => void; 115 | protected _processClosed: Promise; 116 | protected _thrownError?: Error; 117 | 118 | public get process(): ChildProcess | undefined { 119 | return this._process; 120 | } 121 | 122 | public get pid(): number | undefined { 123 | return this._process?.pid; 124 | } 125 | 126 | public get exitCode(): number | undefined { 127 | if (this._process && this._process.exitCode !== null) { 128 | return this._process.exitCode; 129 | } 130 | return undefined; 131 | } 132 | 133 | public constructor( 134 | command: string, 135 | args?: string[], 136 | options?: Partial 137 | ) { 138 | this._options = { 139 | ...defaultOptions, 140 | ...options 141 | }; 142 | this._command = command; 143 | this._args = args ?? []; 144 | this._processClosed = new Promise((resolve) => { 145 | this._resolveClose = resolve; 146 | }); 147 | } 148 | 149 | public kill(signal?: KillSignal): boolean { 150 | return this._process?.kill(signal) === true; 151 | } 152 | 153 | public get aborted(): boolean { 154 | return this._aborted; 155 | } 156 | 157 | public get killed(): boolean { 158 | return this._process?.killed === true; 159 | } 160 | 161 | public pipe( 162 | command: string, 163 | args?: string[], 164 | options?: Partial 165 | ): Result { 166 | return exec(command, args, { 167 | ...options, 168 | stdin: this 169 | }); 170 | } 171 | 172 | async *[Symbol.asyncIterator](): AsyncIterator { 173 | const proc = this._process; 174 | 175 | if (!proc) { 176 | return; 177 | } 178 | 179 | const streams: Readable[] = []; 180 | 181 | if (this._streamErr) { 182 | streams.push(this._streamErr); 183 | } 184 | if (this._streamOut) { 185 | streams.push(this._streamOut); 186 | } 187 | 188 | const streamCombined = combineStreams(streams); 189 | 190 | const rl = readline.createInterface({ 191 | input: streamCombined 192 | }); 193 | 194 | for await (const chunk of rl) { 195 | yield chunk.toString(); 196 | } 197 | 198 | await this._processClosed; 199 | 200 | proc.removeAllListeners(); 201 | 202 | if (this._thrownError) { 203 | throw this._thrownError; 204 | } 205 | 206 | if ( 207 | this._options?.throwOnError && 208 | this.exitCode !== 0 && 209 | this.exitCode !== undefined 210 | ) { 211 | throw new NonZeroExitError(this); 212 | } 213 | } 214 | 215 | protected async _waitForOutput(): Promise { 216 | const proc = this._process; 217 | 218 | if (!proc) { 219 | throw new Error('No process was started'); 220 | } 221 | 222 | const [stdout, stderr] = await Promise.all([ 223 | this._streamOut ? readStream(this._streamOut) : '', 224 | this._streamErr ? readStream(this._streamErr) : '' 225 | ]); 226 | 227 | await this._processClosed; 228 | 229 | if (this._options?.stdin) { 230 | await this._options.stdin; 231 | } 232 | 233 | proc.removeAllListeners(); 234 | 235 | if (this._thrownError) { 236 | throw this._thrownError; 237 | } 238 | 239 | const result: Output = { 240 | stderr, 241 | stdout, 242 | exitCode: this.exitCode 243 | }; 244 | 245 | if ( 246 | this._options.throwOnError && 247 | this.exitCode !== 0 && 248 | this.exitCode !== undefined 249 | ) { 250 | throw new NonZeroExitError(this, result); 251 | } 252 | 253 | return result; 254 | } 255 | 256 | public then( 257 | onfulfilled?: ((value: Output) => TResult1 | PromiseLike) | null, 258 | onrejected?: ((reason: unknown) => TResult2 | PromiseLike) | null 259 | ): Promise { 260 | return this._waitForOutput().then(onfulfilled, onrejected); 261 | } 262 | 263 | protected _streamOut?: Readable; 264 | protected _streamErr?: Readable; 265 | 266 | public spawn(): void { 267 | const cwd = getCwd(); 268 | const options = this._options; 269 | const nodeOptions = { 270 | ...defaultNodeOptions, 271 | ...options.nodeOptions 272 | }; 273 | const signals: AbortSignal[] = []; 274 | 275 | this._resetState(); 276 | 277 | if (options.timeout !== undefined) { 278 | signals.push(AbortSignal.timeout(options.timeout)); 279 | } 280 | 281 | if (options.signal !== undefined) { 282 | signals.push(options.signal); 283 | } 284 | 285 | if (options.persist === true) { 286 | nodeOptions.detached = true; 287 | } 288 | 289 | if (signals.length > 0) { 290 | nodeOptions.signal = combineSignals(signals); 291 | } 292 | 293 | nodeOptions.env = computeEnv(cwd, nodeOptions.env); 294 | 295 | const {command: normalisedCommand, args: normalisedArgs} = 296 | normaliseCommandAndArgs(this._command, this._args); 297 | 298 | const crossResult = _parse(normalisedCommand, normalisedArgs, nodeOptions); 299 | 300 | const handle = spawn( 301 | crossResult.command, 302 | crossResult.args, 303 | crossResult.options 304 | ); 305 | 306 | if (handle.stderr) { 307 | this._streamErr = handle.stderr; 308 | } 309 | if (handle.stdout) { 310 | this._streamOut = handle.stdout; 311 | } 312 | 313 | this._process = handle; 314 | handle.once('error', this._onError); 315 | handle.once('close', this._onClose); 316 | 317 | if (options.stdin !== undefined && handle.stdin && options.stdin.process) { 318 | const {stdout} = options.stdin.process; 319 | if (stdout) { 320 | stdout.pipe(handle.stdin); 321 | } 322 | } 323 | } 324 | 325 | protected _resetState(): void { 326 | this._aborted = false; 327 | this._processClosed = new Promise((resolve) => { 328 | this._resolveClose = resolve; 329 | }); 330 | this._thrownError = undefined; 331 | } 332 | 333 | protected _onError = (err: Error): void => { 334 | if ( 335 | err.name === 'AbortError' && 336 | (!(err.cause instanceof Error) || err.cause.name !== 'TimeoutError') 337 | ) { 338 | this._aborted = true; 339 | return; 340 | } 341 | this._thrownError = err; 342 | }; 343 | 344 | protected _onClose = (): void => { 345 | if (this._resolveClose) { 346 | this._resolveClose(); 347 | } 348 | }; 349 | } 350 | 351 | export const x: TinyExec = (command, args, userOptions) => { 352 | const proc = new ExecProcess(command, args, userOptions); 353 | 354 | proc.spawn(); 355 | 356 | return proc; 357 | }; 358 | 359 | export const exec = x; 360 | --------------------------------------------------------------------------------