Skip to content

Instantly share code, notes, and snippets.

@5alamander
Created November 8, 2016 10:18
Show Gist options
  • Save 5alamander/193e2b419a97caaabdc55c020f06b98c to your computer and use it in GitHub Desktop.
Save 5alamander/193e2b419a97caaabdc55c020f06b98c to your computer and use it in GitHub Desktop.
a prompt with history
// IMPORTANT: choose one
var RL_LIB = "libreadline"; // NOTE: libreadline is GPL
//var RL_LIB = "libedit";
var HISTORY_FILE = require('path').join(process.env.HOME, '.mal-history');
var ffi = require('ffi'),
fs = require('fs');
var rllib = ffi.Library(RL_LIB, {
'readline': [ 'string', [ 'string' ] ],
'add_history': [ 'int', [ 'string' ] ]});
var rl_history_loaded = false;
export function readline(prompt) {
prompt = prompt || "user> ";
if (!rl_history_loaded) {
rl_history_loaded = true;
var lines = [];
if (fs.existsSync(HISTORY_FILE)) {
lines = fs.readFileSync(HISTORY_FILE).toString().split("\n");
}
// Max of 2000 lines
lines = lines.slice(Math.max(lines.length - 2000, 0));
for (var i=0; i<lines.length; i++) {
if (lines[i]) { rllib.add_history(lines[i]); }
}
}
var line = rllib.readline(prompt);
if (line) {
rllib.add_history(line);
try {
fs.appendFileSync(HISTORY_FILE, line + "\n");
} catch (exc) {
// ignored
}
}
return line;
};
while (true) {
let line = readline('client> ')
if (line == null) break
if (line) {
console.log(REP(line))
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment