Get Even More Visitors To Your Blog, Upgrade To A Business Listing >>

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

Tags: repl load script

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

Problem

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?

Problem courtesy of: hugomg

Solution

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())
Solution courtesy of: vossad01

Discussion

View additional discussion.



This post first appeared on Node.js Recipes, please read the originial post: here

Share the post

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

×

Subscribe to Node.js Recipes

Get updates delivered right to your inbox!

Thank you for your subscription

×