
High-level support for running, observing, and interacting with child processes
in Node.js 4 and above.
const ObservableProcess = require("observableProcess")
var myProcess = new ObservableProcess("echo hello")
myProcess.on("ended", function({ exitCode }) {
})
You can also provide the process to run as an argv array:
myProcess = new ObservableProcess(["echo", "hello"])
Set the working directory of the subshell
myProcess = new ObservableProcess("echo hello", { cwd: "~/tmp" })
Set environment variables in the subshell
myProcess = new ObservableProcess("echo hello", { env: { foo: "bar" } })
Working with output
ObservableProcess provides powerful mechanisms to work with output
generated by the subprocess.
By default, the output of the observed process is printed on the console.
You can also customize logging by providing custom stdout and stderr objects
(which needs to have the method write):
const myStdOut = {
write: text => {
}
}
const myStdErr = {
write: text => {
}
}
myProcess = new ObservableProcess("echo hello", {
stdout: myStdOut,
stderr: myStdErr
})
You can use dimConsole
to print output from the subshell dimmed,
so that it is easy to distinguish from output of the main thread.
const dimConsole = require("dim-console")
myProcess = new ObservableProcess("echo hello", {
stdout: dimConsole.stdout,
stderr: dimConsole.stderr
})
To get more detailed output like lifecycle events of the subshell
in the error stream:
myProcess = new ObservableProcess("echo hello", { verbose: true })
You can retrieve the output that has accumulated so far to stdout and stderr
merged into a single string:
myProcess.fullOutput()
You can be notified when the process prints given text on stdout or stderr.
This is useful for waiting until slow-starting services are fully booted up.
myProcess.waitForText("listening on port 3000").then(function() {
})
To disable output altogether:
myProcess = new ObservableProcess("my-server", { stdout: null, stderr: null })
Input
You can enter text into the running process via:
myProcess.enter("text")
Kill the process
If the process is running, you can kill it via:
myProcess.kill()
This sets the killed property on the ObservableProcess instance,
so that manual kills can be distinguished from crashes.
To let ObservableProcess notify you when a process ended:
myProcess.waitForEnd(({ exitCode, killed }) => {
})
You can also access the exit code from the process object:
myProcess.exitCode
Get the process id
myProcess.pid()
related libraries
- nexpect:
Allows to define expectations on command output,
and send it input,
but doesn't allow to add more listeners to existing long-running processes,
which makes declarative testing hard.