You can wrap `spawn` in a `setImmediate`, so that others get a chance to attach their events.
On 06/18/2013 04:19 AM, Ryan Schmidt wrote: > Per previous threads, I'm implementing a transform stream around a particular > command line program for use in a web service. How should the stream report > errors? > > In the case of the _transform and _flush functions that I'm supposed to > implement, they're given a callback parameter, so I can "callback(new > Error(…))". That's easy, but what about in other situations, like the > constructor? > > In the constructor of my custom transform stream, I spawn a process: > > var process = this._process = spawn(options.command, options.args, > options.env); > > If the process closes with a non-zero exit code or crashes, I want to be able > to report that, not just to the server's console, but also to the web browser > of the user who made the request that started the process: > > process.on('close', function(code, signal) { > if (signal !== null) { > … > } else if (code !== 0) { > … > } > self.emit('close'); > }); > > If a problem occurred, should I "throw new Error(…)" or "self.emit('error', > new Error(…)"? > > I was emitting the error, but am having trouble making that work in code > running directly in the constructor. Let's say I want to allow only a few > different commands ("foo" and "bar") to be run: > > if (!~['foo', 'bar'].indexOf(options.command)) { > this.emit('error', new Error('Invalid command: ' + options.command)); > } > > If I emit an error like that, then the node program exits saying there was no > listener attached to the stream listening for the error event. But I cannot > attach a listener to the stream until after the constructor has finished and > has returned the stream object to me. > > Should I instead throw the error? If so, do I just use a try{}catch{} block > whenever I create such a stream? > > > Passing Error objects to a callback is straightforward, but other methods of > error handling in node are still very confusing to me, especially try/catch. > Guidance would be appreciated. > >
signature.asc
Description: OpenPGP digital signature