diff --git a/src/index.js b/src/index.js index 63c0f0f..983a592 100644 --- a/src/index.js +++ b/src/index.js @@ -102,12 +102,21 @@ function run_scratch_file(filename) { } vm.runtime.on('QUESTION', function (question) { - if (question !== null) { - if (question === 'read_token') { - vm.runtime.emit('ANSWER', Kattio.nextToken()); - } else { - vm.runtime.emit('ANSWER', Kattio.nextLine()); + try { + if (question !== null) { + if (question === 'read_token') { + vm.runtime.emit('ANSWER', Kattio.nextToken()); + } else { + vm.runtime.emit('ANSWER', Kattio.nextLine()); + } } + } catch (e) { + writeStderrSync( + 'scratch-vm encountered an error: Could not read input: ' + + e.message + + '\n' + ); + process.exit(1); } }); diff --git a/src/kattio.js b/src/kattio.js index ecd14a1..2db1107 100644 --- a/src/kattio.js +++ b/src/kattio.js @@ -32,7 +32,10 @@ const Kattio = { _readUntil: function (stop) { this._ensure(); - if (this._bufPos === this._bufLen) throw new Error('eof'); + if (this._bufPos === this._bufLen) { + throw new Error('End of file reached'); + } + var start = this._bufPos; var before = null; for (;;) { @@ -51,7 +54,9 @@ const Kattio = { if (this._bufPos === this._bufLen || stop(this._buf[this._bufPos])) break; this._bufPos++; } - if (!before) return this._buf.toString('utf8', start, this._bufPos); + if (!before) { + return this._buf.toString('utf8', start, this._bufPos); + } var after = this._buf.slice(start, this._bufPos); var res = Buffer.alloc(before.length + after.length); before.copy(res);