Commit 4915ff3
Changed files (5)
examples/background-process.mjs
@@ -0,0 +1,25 @@
+#!/usr/bin/env zx
+
+// Copyright 2021 Google LLC
+//
+// Licensed under the Apache License, Version 2.0 (the "License");
+// you may not use this file except in compliance with the License.
+// You may obtain a copy of the License at
+//
+// https://www.apache.org/licenses/LICENSE-2.0
+//
+// Unless required by applicable law or agreed to in writing, software
+// distributed under the License is distributed on an "AS IS" BASIS,
+// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+// See the License for the specific language governing permissions and
+// limitations under the License.
+
+let serve = $`npx serve`
+
+for await (let chunk of serve.stdout) {
+ if (chunk.includes('Accepting connections')) break
+}
+
+await $`curl http://localhost:5000`
+
+serve.kill('SIGINT')
index.d.ts
@@ -40,6 +40,7 @@ export interface ProcessPromise<T> extends Promise<T> {
readonly exitCode: Promise<number>
pipe(dest: ProcessPromise<ProcessOutput> | Writable): ProcessPromise<ProcessOutput>
+ kill(signal?: string | number): Promise<void>
}
export class ProcessOutput {
index.mjs
@@ -23,6 +23,7 @@ import {default as nodeFetch} from 'node-fetch'
import which from 'which'
import chalk from 'chalk'
import minimist from 'minimist'
+import psTreeModule from 'ps-tree'
export {chalk, fs, os, path}
export const sleep = promisify(setTimeout)
@@ -31,6 +32,7 @@ export const globby = Object.assign(function globby(...args) {
return globbyModule.globby(...args)
}, globbyModule)
export const glob = globby
+const psTree = promisify(psTreeModule)
export function registerGlobals() {
Object.assign(global, {
@@ -230,6 +232,20 @@ export class ProcessPromise extends Promise {
return this
}
}
+
+ async kill(signal = 'SIGTERM') {
+ let children = await psTree(this.child.pid)
+ for (const p of children) {
+ try {
+ process.kill(p.PID, signal)
+ } catch (e) {
+ }
+ }
+ try {
+ process.kill(this.child.pid, signal)
+ } catch (e) {
+ }
+ }
}
export class ProcessOutput extends Error {
package.json
@@ -28,6 +28,7 @@
"globby": "^12.0.1",
"minimist": "^1.2.5",
"node-fetch": "^2.6.1",
+ "ps-tree": "^1.2.0",
"which": "^2.0.2"
},
"devDependencies": {
README.md
@@ -108,6 +108,7 @@ class ProcessPromise<T> extends Promise<T> {
readonly stderr: Readable
readonly exitCode: Promise<number>
pipe(dest): ProcessPromise<T>
+ kill(signal = 'SIGTERM'): Promise<void>
}
```