constructor(opts={}) {
    super();

    this.in = opts.in || process.stdin;
    this.out = opts.out || process.stdout;

    const rl = readline.createInterface(this.in);
    readline.emitKeypressEvents(this.in, rl);

    if (this.in.isTTY) this.in.setRawMode(true);

    const keypress = (str, key) => {
      let a = action(key);
      if (a === false) {
        this._ && this._(str, key);
      } else if (typeof this[a] === 'function') {
        this[a](key);
      } else {
        this.bell();
      }
    };

    const close = () => {
      this.out.write(cursor.show);
      this.in.removeListener('keypress', keypress);
      if (this.in.isTTY) this.in.setRawMode(false);
      rl.close();
      this.emit(this.aborted ? 'abort' : 'submit', this.value);
    };
    this.close = close;

    this.in.on('keypress', keypress);
  }
 ].forEach(function (keypresses) {
   fi = new FakeInput();
   callCount = 0;
   var remainingKeypresses = keypresses.slice();
   function keypressListener (ch, key) {
     callCount++;
     if (ch) assert(!key.code);
     assert.equal(key.sequence, remainingKeypresses.shift());
   };
   readline.emitKeypressEvents(fi);
   fi.on('keypress', keypressListener);
   fi.emit('data', keypresses.join(''));
   assert.equal(callCount, keypresses.length);
   assert.equal(remainingKeypresses.length, 0);
   fi.removeListener('keypress', keypressListener);
   fi.emit('data', ''); // removes listener
 });
示例#3
0
文件: app.js 项目: kolja/nodeshell
//            console.error(ex.toString());
//            doneCB(util.inspect(ex));
//        }
    }
});
var parser = new Parser(
    commands
//    ,
//    cb: function () {
//        line.setPrompt(getPrompt());
//        line._refreshLine();
//    }
);
var stdin = process.stdin;

readline.emitKeypressEvents(stdin);

stdin.setRawMode(true);

var keyHandler = new KeyHandler({
    input: stdin,
    output: process.stdout,
    line: line
});

function runUserFile () {
    console.log('this is supposed to read and execute user scripts');
}
runUserFile();

line.setPrompt(getPrompt());
示例#4
0
var dash_button = require('node-dash-button');
var readline = require('readline');
var firebase = require('firebase');

var config = {
  apiKey: "AIzaSyAvO4rci6SDM5wJ0jIeGoBJw9Wj7mnCCAo",
  authDomain: "project-5457323458366770321.firebaseapp.com",
  databaseURL: "https://project-5457323458366770321.firebaseio.com",
  storageBucket: "",
};
app = firebase.initializeApp(config);
var name = "1466513558321";
readline.emitKeypressEvents(process.stdin);
process.stdin.setRawMode(true);

var home_up = "08:00:27:54:4c:c1"
var away_up = "2"
var home_down = "3"
var away_down = "4"



var dash = dash_button([home_up, away_up, home_down, away_down]);
dash.on("detected", function(dash_id){
    switch(dash_id){
        case home_up:
            handler('home', 1);
            break;
        case away_up:
            handler('away', 1);
            break;
'use strict';
// emitKeypressEvents is thoroughly tested in test-readline-keys.js.
// However, that test calls it implicitly. This is just a quick sanity check
// to verify that it works when called explicitly.

require('../common');
const assert = require('assert');
const readline = require('readline');
const PassThrough = require('stream').PassThrough;
const stream = new PassThrough();
const sequence = [];
const keys = [];

readline.emitKeypressEvents(stream);

stream.on('keypress', (s, k) => {
  sequence.push(s);
  keys.push(k);
});

stream.write('foo');

process.on('exit', () => {
  assert.deepStrictEqual(sequence, ['f', 'o', 'o']);
  assert.deepStrictEqual(keys, [
    { sequence: 'f', name: 'f', ctrl: false, meta: false, shift: false },
    { sequence: 'o', name: 'o', ctrl: false, meta: false, shift: false },
    { sequence: 'o', name: 'o', ctrl: false, meta: false, shift: false }
  ]);
});
                  sessions.select({query: {selector: so.selector.normalized}, limit: 1, sort: {started: -1}}, function (err, prev_sessions) {
                    if (err) throw err
                    var prev_session = prev_sessions[0]
                    if (prev_session && !cmd.reset_profit) {
                      if (prev_session.orig_capital && prev_session.orig_price && ((so.mode === 'paper' && !raw_opts.currency_capital && !raw_opts.asset_capital) || (so.mode === 'live' && prev_session.balance.asset == s.balance.asset && prev_session.balance.currency == s.balance.currency))) {
                        s.orig_capital = session.orig_capital = prev_session.orig_capital
                        s.orig_price = session.orig_price = prev_session.orig_price
                        if (so.mode === 'paper') {
                          s.balance = prev_session.balance
                        }
                      }
                    }
                    if(lookback_size = s.lookback.length > so.keep_lookback_periods){
                      s.lookback.splice(-1,1)
                    }

                    forwardScan()
                    setInterval(forwardScan, so.poll_trades)
                    readline.emitKeypressEvents(process.stdin)
                    if (!so.non_interactive && process.stdin.setRawMode) {
                      process.stdin.setRawMode(true)
                      process.stdin.on('keypress', function (key, info) {
                        if (key === 'l') {
                          listKeys()
                        } else if (key === 'b' && !info.ctrl ) {
                          engine.executeSignal('buy')
                          console.log('\nmanual'.grey + ' limit ' + 'BUY'.green + ' command executed'.grey)
                        } else if (key === 'B' && !info.ctrl) {
                          engine.executeSignal('buy', null, null, false, true)
                          console.log('\nmanual'.grey + ' market ' + 'BUY'.green + ' command executed'.grey)
                        } else if (key === 's' && !info.ctrl) {
                          engine.executeSignal('sell')
                          console.log('\nmanual'.grey + ' limit ' + 'SELL'.red + ' command executed'.grey)
                        } else if (key === 'S' && !info.ctrl) {
                          engine.executeSignal('sell', null, null, false, true)
                          console.log('\nmanual'.grey + ' market ' + 'SELL'.red + ' command executed'.grey)
                        } else if ((key === 'c' || key === 'C') && !info.ctrl) {
                          delete s.buy_order
                          delete s.sell_order
                          console.log('\nmanual'.grey + ' order cancel' + ' command executed'.grey)
                        } else if (key === 'm' && !info.ctrl && so.mode === 'live') {
                          so.manual = !so.manual
                          console.log('\nMANUAL trade in LIVE mode: ' + (so.manual ? 'ON'.green.inverse : 'OFF'.red.inverse))
                        } else if (key === 'T' && !info.ctrl) {
                          so.order_type = 'taker'
                          console.log('\n' + 'Taker fees activated'.bgRed)
                        } else if (key === 'M' && !info.ctrl) {
                          so.order_type = 'maker'
                          console.log('\n' + 'Maker fees activated'.black.bgGreen)
                        } else if (key === 'o' && !info.ctrl) {
                          listOptions()
                        } else if (key === 'O' && !info.ctrl) {
                          console.log('\n' + cliff.inspect(so))
                        } else if (key === 'P' && !info.ctrl) {
                          console.log('\nWriting statistics...'.grey)
                          printTrade(false)
                        } else if (key === 'X' && !info.ctrl) {
                          console.log('\nExiting... ' + '\nWriting statistics...'.grey)
                          printTrade(true)
                        } else if (key === 'd' && !info.ctrl) {
                          console.log('\nDumping statistics...'.grey)
                          printTrade(false, true)
                        } else if (key === 'D' && !info.ctrl) {
                          console.log('\nDumping statistics...'.grey)
                          toggleStats()
                        } else if (key === 'L' && !info.ctrl) {
                          so.debug = !so.debug
                          console.log('\nDEBUG mode: ' + (so.debug ? 'ON'.green.inverse : 'OFF'.red.inverse))
                        } else if (info.name === 'c' && info.ctrl) {
                          // @todo: cancel open orders before exit
                          console.log()
                          process.exit()
                        }
                      })
                    }
                  })
示例#7
0
文件: index.js 项目: rpl/web-ext
export function defaultReloadStrategy(
  {
    artifactsDir,
    extensionRunner,
    ignoreFiles,
    noInput = false,
    sourceDir,
  }: ReloadStrategyParams,
  {
    createWatcher = defaultWatcherCreator,
    stdin = process.stdin,
    kill = process.kill,
  }: ReloadStrategyOptions = {}
): void {
  const allowInput = !noInput;
  if (!allowInput) {
    log.debug('Input has been disabled because of noInput==true');
  }

  const watcher: Watchpack = createWatcher({
    reloadExtension: (watchedSourceDir) => {
      extensionRunner.reloadExtensionBySourceDir(watchedSourceDir);
    },
    sourceDir,
    artifactsDir,
    ignoreFiles,
  });

  extensionRunner.registerCleanup(() => {
    watcher.close();
    if (allowInput) {
      stdin.pause();
    }
  });

  if (allowInput && isTTY(stdin)) {
    readline.emitKeypressEvents(stdin);
    setRawMode(stdin, true);

    const keypressUsageInfo = 'Press R to reload (and Ctrl-C to quit)';

    // NOTE: this `Promise.resolve().then(...)` is basically used to spawn a "co-routine"
    // that is executed before the callback attached to the Promise returned by this function
    // (and it allows the `run` function to not be stuck in the while loop).
    Promise.resolve().then(async function() {
      log.info(keypressUsageInfo);

      let userExit = false;

      while (!userExit) {
        const keyPressed = await new Promise((resolve) => {
          stdin.once('keypress', (str, key) => resolve(key));
        });

        if (keyPressed.ctrl && keyPressed.name === 'c') {
          userExit = true;
        } else if (keyPressed.name === 'z') {
          // Prepare to suspend.

          // NOTE: Switch the raw mode off before suspending (needed to make the keypress event
          // to work correctly when the nodejs process is resumed).
          setRawMode(stdin, false);

          log.info('\nweb-ext has been suspended on user request');
          kill(process.pid, 'SIGTSTP');

          // Prepare to resume.

          log.info(`\nweb-ext has been resumed. ${keypressUsageInfo}`);

          // Switch the raw mode on on resume.
          setRawMode(stdin, true);
        } else if (keyPressed.name === 'r') {
          log.debug('Reloading installed extensions on user request');
          extensionRunner.reloadAllExtensions();
        }
      }

      log.info('\nExiting web-ext on user request');
      extensionRunner.exit();
    });
  }
}
示例#8
0
BEAST.init = () => {
	BEAST.debugging.headline(`DEBUG|INFO`, 99);

	//testing screen size and exiting on error
	let error = BEAST.checkSize();
	if( error !== '' ) {
		console.log( error );
		process.exit( 1 );
	}

	BEAST.RL = Readline.createInterface({ //create the readline interface
		input: process.stdin,
		output: customStdout,
		terminal: true,
		historySize: 0,
	});

	Readline.emitKeypressEvents( process.stdin );
	process.stdin.setEncoding('utf8');

	if(process.stdin.isTTY) {
		process.stdin.setRawMode( true );
	}


	process.on("SIGWINCH", () => { //redraw frame and board on terminal resize
		BEAST.draw.frame();
		BEAST.draw.score();
		BEAST.draw.board();
	});


	process.stdin.on("keypress", (chunk, key) => { //redraw frame and board on terminal resize
		BEAST.RL.clearLine();

		if( key.name === 'right' ) {
			BEAST.hero.move( 'x', 1 );
		}
		else if( key.name === 'left' ) {
			BEAST.hero.move( 'x', -1 );
		}
		else if( key.name === 'up' ) {
			BEAST.hero.move( 'y', -1 );
		}
		else if( key.name === 'down' ) {
			BEAST.hero.move( 'y', 1 );
		}
		else if( key.name === 'q' ) {
			process.exit(0);
		}
		else {
			return;
		}
	});


	// BEAST.RL.on("close", () => { //redraw frame and board on terminal resize
	// 	customStdout.muted = false;

	// 	Readline.cursorTo( BEAST.RL, 0, 0 ); //go to top of board
	// 	Readline.clearScreenDown( BEAST.RL ); //clear screen

	// 	console.log(`\n   Good bye\n`);

	// 	process.exit(0);
	// });


	BEAST.scaffolding.init();
	BEAST.draw.init();
	BEAST.beasts.init();
};
示例#9
-1
文件: utils.js 项目: sstur/drift
exports.getKeypressEmitter = function open(input) {
  readline.emitKeypressEvents(input);
  var keyEmitter = new EventEmitter();
  input.on('keypress', function(ch, key) {
    if (!key) return;
    if (key.ctrl && key.name == 'c') {
      process.exit();
    }
    var list = [];
    if (key.ctrl) list.push('ctrl');
    if (key.shift) list.push('shift');
    if (key.meta) list.push('meta');
    list.push(key.name);
    var keys = list.join(':');
    keyEmitter.emit('*', keys);
    keyEmitter.emit(keys);
  });
  input.setRawMode(true);
  input.resume();
  return keyEmitter;
};