Skip to content

Commit 8da89c9

Browse files
committed
Merge pull request #2 from caarbon/feature/custom-modes
Moving to `parser`
2 parents 29595a4 + a4bfc3c commit 8da89c9

File tree

2 files changed

+10
-8
lines changed

2 files changed

+10
-8
lines changed

README.md

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -129,6 +129,7 @@ Creates an instance of `PythonShell` and starts the Python process
129129
* `text`: each line of data (ending with "\n") is emitted as a message (default)
130130
* `json`: each line of data (ending with "\n") is parsed as JSON and emitted as a message
131131
* `binary`: data is streamed as-is through `stdout` and `stdin`
132+
* `parser`: each line of data (ending with "\n") is parsed with this customer parser (overrides `mode`)
132133
* `pythonPath`: The path where to locate the "python" executable. Default: "python"
133134
* `pythonOptions`: Array of option switches to pass to "python"
134135
* `scriptPath`: The default path where to look for scripts. Default: "./python"

index.js

Lines changed: 9 additions & 8 deletions
Original file line numberDiff line numberDiff line change
@@ -42,6 +42,7 @@ var PythonShell = function (script, options) {
4242
this.script = path.join(options.scriptPath || './python', script);
4343
this.command = pythonOptions.concat(this.script, scriptArgs);
4444
this.mode = options.mode || 'text';
45+
this.parser = options.parser;
4546
this.terminated = false;
4647
this.childProcess = spawn(pythonPath, this.command, options);
4748

@@ -185,21 +186,21 @@ PythonShell.prototype.receive = function (data) {
185186
this._remaining = lastLine;
186187

187188
lines.forEach(function (line) {
188-
if (self.mode === 'json') {
189+
if (self.parser) {
189190
try {
190-
self.emit('message', JSON.parse(line));
191-
} catch (err) {
191+
self.emit('message', self.parser(line));
192+
} catch(err) {
192193
self.emit('error', extend(
193-
new Error('invalid JSON message: ' + data + ' >> ' + err),
194+
new Error('invalid message: ' + data + ' >> ' + err),
194195
{ inner: err, data: line}
195196
));
196197
}
197-
} else if (typeof self.mode === 'function') {
198+
} else if (self.mode === 'json') {
198199
try {
199-
self.emit('message', self.mode(line));
200-
} catch(err) {
200+
self.emit('message', JSON.parse(line));
201+
} catch (err) {
201202
self.emit('error', extend(
202-
new Error('invalid message: ' + data + ' >> ' + err),
203+
new Error('invalid JSON message: ' + data + ' >> ' + err),
203204
{ inner: err, data: line}
204205
));
205206
}

0 commit comments

Comments
 (0)