|
| 1 | +// Copyright 2014 Runtime.JS project authors |
| 2 | +// |
| 3 | +// Licensed under the Apache License, Version 2.0 (the "License"); |
| 4 | +// you may not use this file except in compliance with the License. |
| 5 | +// You may obtain a copy of the License at |
| 6 | +// |
| 7 | +// http://www.apache.org/licenses/LICENSE-2.0 |
| 8 | +// |
| 9 | +// Unless required by applicable law or agreed to in writing, software |
| 10 | +// distributed under the License is distributed on an "AS IS" BASIS, |
| 11 | +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. |
| 12 | +// See the License for the specific language governing permissions and |
| 13 | +// limitations under the License. |
| 14 | + |
| 15 | +function exit() { |
| 16 | + runtime.exit(); |
| 17 | +} |
| 18 | + |
| 19 | +(function(args) { |
| 20 | + "use strict"; |
| 21 | + |
| 22 | + if ('string' === typeof args.data.command && '' !== args.data.command) { |
| 23 | + evalLine(args.data.command); |
| 24 | + return; |
| 25 | + } |
| 26 | + |
| 27 | + args.env.stdout('JavaScript REPL (special commands: exit)\n', {fg: 'darkgray'}); |
| 28 | + |
| 29 | + function readLine(cb) { |
| 30 | + args.env.stdout('> ', {fg: 'lightgreen'}); |
| 31 | + args.env.stdin({ |
| 32 | + mode: 'line', |
| 33 | + onData: function(data) { |
| 34 | + cb(data.text); |
| 35 | + } |
| 36 | + }); |
| 37 | + } |
| 38 | + |
| 39 | + function evalLine(text) { |
| 40 | + text = text.trim(); |
| 41 | + |
| 42 | + if ('' === text) { |
| 43 | + return; |
| 44 | + } |
| 45 | + |
| 46 | + try { |
| 47 | + var result = (1, eval)(text); |
| 48 | + args.env.stdout(result + '\n', {fg: 'lightgray'}); |
| 49 | + } catch (err) { |
| 50 | + console.error(err.toString()); |
| 51 | + } |
| 52 | + } |
| 53 | + |
| 54 | + readLine(function onData(text) { |
| 55 | + if ('exit' === text.trim()) { |
| 56 | + runtime.exit(); |
| 57 | + } |
| 58 | + |
| 59 | + evalLine(text); |
| 60 | + readLine(onData); |
| 61 | + }); |
| 62 | + |
| 63 | +})(runtime.args()); |
0 commit comments