Skip to content

Catch the status of a child process as a stream error #31

@tyrak

Description

@tyrak

I am using duplexify to create a duplex stream out of a child process. This enables me to create complex pipelines, combining processes with other streams. So, I wrote a simple function that wraps duplexify and child_process.spawn as follows:

function run(program, args) {
	const child = spawn(program, args, {
		stdio: ["pipe", "pipe", "inherit"],
	});
	const stream = duplexify(child.stdin, child.stdout);
	child.on("error", (err) => {
		stream.destroy(err);
	});
	return stream;
}

Now I can use the stream returned by run with stream.pipeline. The only issue that I have with this solution is that I would like run to wait for the child processes' exit status, and if it is not zero, forward an error to the duplex stream. I tried to address this by adding a final method as follows:

function run(program, args) {
	const child = spawn(program, args, {
		stdio: ["pipe", "pipe", "inherit"],
	});
	const final = (stream, callback) => {
		child.on("exit", (code, signal) => {
			if (code !== 0)
				callback(new Error("child process failed"));
			else
				callback();
		});
	};
	const stream = duplexify(child.stdin, child.stdout, {final});
	child.on("error", (err) => {
		stream.destroy(err);
	});
	return stream;
}

but the final function never gets called by duplexify. Is there a way to solve this issue with duplexify?

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions