问题
When I run node
from the command line with no arguments, I enter an interactive shell. If I execute some commands, exit node, and restart node, the up arrow doesn't do anything (I'd like it scroll through my previous commands).
Is there a way I can invoke node interactively such that it will remember my old commands?
回答1:
You could use rlwrap to store node.js REPL commands in a history file.
First, install rlwrap (done easily with a package manager like apt-get or brew etc).
Then add an alias for node:
alias node='env NODE_NO_READLINE=1 rlwrap node'
I'm on OSX so I add that alias to my ~/.bash_profile
file, and would reload my bash_profile file via source ~/.bash_profile
.. and I'm good to go!
Hope this helps!
回答2:
I found a nice little project, which solves the problem:
https://www.npmjs.org/package/repl.history
install using npm (npm install -g repl.history
)
and run repl.history
on the command line.
回答3:
io.js 2.0 includes support for persistent REPL history.
env NODE_REPL_HISTORY_FILE=$HOME/.node_history iojs
The maximum length of the history can be set with NODE_REPL_HISTORY_SIZE
, which defaults to 1000.
In io.js 3.0+, REPL history is enabled by default and NODE_REPL_HISTORY_FILE
is deprecated in favor of NODE_REPL_HISTORY
(default: ~/.node_repl_history
).
回答4:
I like the combination of both dreampulse's and badsyntax's answers. With repl.history, plus an addition to my .bash_profile I get the behavior I expect, which is command history and syntax highlighting in the node interactive shell, but bypassing repl when called with arguments (to run a script).
npm install -g repl.history
Then edit your ~/.bash_profile, adding:
function node(){
if test "$#" -lt 1; then repl.history
else env node $@; fi; }
Now restart your shell or run . ~/.bash_profile
and you're good to go.
Now running
$ node
will open the repl.history nodejs interactive shell, and
$ node program.js [...]
will run program.js with node as expected.
回答5:
Node supports this natively.
When in node REPL just issue the following command to save the history:
$> .save ./file/to/save.js
Reference: Commands and Special Keys
回答6:
As well check file .node_repl_history in user home directory.
来源:https://stackoverflow.com/questions/18511787/is-there-a-way-to-have-node-preserve-command-line-history-between-sessions