How do I load my script into the node.js REPL?

I have a script foo.js that contains some functions I want to play with in the REPL.

Is there a way to have node execute my script and then jump into a REPL with all the declared globals, like I can with python -i foo.py or ghci foo.hs ?


There is still nothing built-in to provide the exact functionality you describe. However, an alternative to using require it to use the .load command within the REPL, like such:

.load foo.js

It loads the file in line by line just as if you had typed it in the REPL. Unlike require this pollutes the REPL history with the commands you loaded. However, it has the advantage of being repeatable because it is not cached like require .

Which is better for you will depend on your use case.


Edit: It has limited applicability because it does not work in strict mode, but three years later I have learned that if your script does not have 'use strict' , you can use eval to load your script without polluting the REPL history:

var fs = require('fs');
eval(fs.readFileSync('foo.js').toString())

I created replpad since I got tired of reloading the script repeatedly.

Simply install it via: npm install -g replpad

Then use it by running: replpad

If you want it to watch all files in the current and all subdirectories and pipe them into the repl when they change do: replpad .

Check out the videos on the site to get a better idea of how it works and learn about some other nice features that it has like these:

  • access core module docs in the repl via the dox() function that is added to every core function, ie fs.readdir.dox()
  • access user module readmes in the repl via the dox() function that is added to every module installed via npm, ie marked.dox()
  • access function's highlighted source code , info on where function was defined (file, linenumber) and function comments and/or jsdocs where possible via the src property that is added to every function, ie express.logger.src
  • scriptie-talkie support (see .talk command)
  • adds commands and keyboard shortcuts
  • vim key bindings
  • key map support
  • parens matching via match token plugin
  • appends code entered in repl back to file via keyboard shortcut or .append command

  • I made Vorpal.js, which handles this problem by turning your node add into an interactive CLI. It supports a REPL extension, which drops you into a REPL within the context of your running app.

    var vorpal = require('vorpal')();
    var repl = require('vorpal-repl');
    
    vorpal
      .delimiter('myapp>')
      .use(repl)
      .show()
      .parse(process.argv); 
    

    Then you can run the app and it will drop into a REPL.

    $ node myapp.js repl
    myapp> repl: 
    
    链接地址: http://www.djcxy.com/p/97022.html

    上一篇: 将多个Coffeescript文件加入一个文件? (多个子目录)

    下一篇: 如何将我的脚本加载到node.js REPL中?