Is there a way to have node preserve command line history between sessions?

匆匆过客 提交于 2019-11-28 21:13:55

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!

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.

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).

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.

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

As well check file .node_repl_history in user home directory.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!