From c83c0105b6ff7770319c135c40d82d0f1cd78928 Mon Sep 17 00:00:00 2001 From: Sami Samhuri Date: Sat, 5 Nov 2011 16:26:46 -0700 Subject: [PATCH] add history file support to repl.js --- repl.js | 42 +++++++++++++++++++++++++++++++++++++++++- 1 file changed, 41 insertions(+), 1 deletion(-) diff --git a/repl.js b/repl.js index 8c39f37..8bf2218 100755 --- a/repl.js +++ b/repl.js @@ -1,3 +1,43 @@ #!/usr/bin/env node -require('./lib/index').startRepl() +var fs = require('fs') + , path = require('path') + , repl = require('./lib/index').startRepl() + , DefaultHistoryFile = path.join(process.env.HOME, '.node_history') + , historyFile + +if ('NODE_HISTORY' in process.env) + historyFile = process.env.NODE_HISTORY +else + historyFile = DefaultHistoryFile + +// restore history immediately +if (historyFile) { + try { + fs.statSync(historyFile) + var json = fs.readFileSync(historyFile) + repl.rli.history = JSON.parse(json) + } + catch (e) { + if (e.code !== 'ENOENT') { + console.error('!!! Error reading history from ' + historyFile) + if (e.message === 'Unexpected token ILLEGAL') { + console.error('is this a JSON array of strings? -> ' + json) + } + else { + console.error(e.message) + } + } + } + + // save history on exit + process.on('exit', function() { + try { + fs.writeFileSync(historyFile, JSON.stringify(repl.rli.history)) + } + catch (e) { + console.error('Error writing history file to ' + historyFile) + console.error(e) + } + }) +}