2011-07-20 118 views
17

有沒有辦法配置node.js的repl?我想在repl開始時自動要求jQuery和下劃線。是否有一個node.js在啓動repl時加載的文件(noderc?)?爲node.js啓動腳本repl

在Python等效與編輯~/.ipython/ipy_user_conf.py

import_mod('sys os datetime re itertools functools') 

回答

16

我不知道任何這樣的配置文件,但如果你想擁有的模塊foobar在REPL是可用,您可以創建一個包含文件myrepl.js

var myrepl = require("repl").start(); 
["foo", "bar"].forEach(function(modName){ 
    myrepl.context[modName] = require(modName); 
}); 

並且當您與node myrepl.js執行它你可用這些模塊REPL。

有了這些知識,你可以把#!/path/to/node頂部和可執行直接使,或者你可以(在https://github.com/joyent/node/blob/master/lib/repl.js檢查可用的源代碼)修改的repl.js模塊的版本或任何:)

+0

非常好!我做了一個用別名加載模塊的變體。 var modules = {jquery:'$',下劃線:'_und'}; for(var mod in modules){ my_repl.context [modules [mod]] = require(mod); } – hekevintran

4

我今天嘗試過,但.start需要一個參數。另外我認爲useGlobal:true很重要。我結束了使用:

var myrepl=require('repl').start({useGlobal:true}); 
myrepl.context['myObj']=require('./myObject'); 

保存這段代碼test.js我可以做一個node test.js然後在REPL訪問myObj

+0

我需要這個來獲得@ nicolaskruchten的例子。感謝你們兩位! – Nate

2

可能是Node.js的新特性(因爲這個問題已經四年了),但you can load and save repl history就像ipython一樣。

.break - While inputting a multi-line expression, sometimes you get lost or just don't care about completing it. .break will start over. 
.clear - Resets the context object to an empty object and clears any multi-line expression. 
.exit - Close the I/O stream, which will cause the REPL to exit. 
.help - Show this list of special commands. 
.save - Save the current REPL session to a file 
    .save ./file/to/save.js 
.load - Load a file into the current REPL session. 
    .load ./file/to/load.js 

我無法弄清楚如何啓動shell時自動執行這一點,但.load something便利足以讓我的時刻。

1

保持簡單的事情就是我的缺點。

repl.js:

// things i want in repl 
global.reload = require('require-nocache')(module) // so I can reload modules as I edit them 
global.r = require('ramda') // <3 http://ramdajs.com/ 
// launch, also capture ref to the repl, in case i want it later 
global.repl = require('repl').start() 

我可以node repl這感覺對調用這個,我不關心全局,因爲我只是在REPL messin'左右。

2

2017年2月 - 雖然我同意接受的答案,但希望在此補充一點評論。

像設置如下(從我的Mac上的主目錄)

.node ├── node_modules │   ├── lodash │   └── ramda ├── package.json └── repl.js

然後REPL。JS可能看起來像如下:

const repl = require('repl'); 

let r = repl.start({ 
    ignoreUndefined: true, 
    replMode: repl.REPL_MODE_STRICT 
}); 

r.context.lodash = require('lodash'); 
r.context.R = require('ramda'); 
// add your dependencies here as you wish.. 

最後,把一個別名到您的.bashrc.zshrc文件等(這取決於你的shell首選項) - 是這樣的:

alias noder='node ~/.node/repl.js'

現在,使用此配置,您只需從命令行輸入noder即可。以上,我還特別指出,我總是喜歡在strict mode,並且不希望undefined打印到控制檯的聲明等

要獲得的最新信息repl,特別repl.start選擇參閱here