1

In node.js you can pass the argument -i to get an interactive console, and then pass -e to evaluate a javascript statement.

I tried running:

$ node -i -e '.load ./someScript.js'
.load someScript.js;
^

SyntaxError: Unexpected token .
    at Object.exports.runInThisContext (vm.js:53:16)
    at Object.<anonymous> ([eval]-wrapper:6:22)
    at Module._compile (module.js:410:26)
    at node.js:578:27
    at nextTickCallbackWith0Args (node.js:419:9)
    at process._tickCallback (node.js:348:13)

And I get an error, but if I try to run the same thing from the interactive node prompt, it loads just fine; i.e.

> .load ./someScript.js

Is there something else I need to do to make this work?

leeand00
  • 25,510
  • 39
  • 140
  • 297

2 Answers2

1

Why can't I eval a .load to start an interactive script in node.js?

Because -e is for evaluating JavaScript code. The interactive REPL's commands aren't JavaScript, they're REPL interactive commands.

This question asks how to go interactive after running a script, which doesn't answer the "why" part (that's why I've posted the above), but its answers may give you some options for the somewhat-implied "...and what do I do instead?" part. :-)

Community
  • 1
  • 1
T.J. Crowder
  • 1,031,962
  • 187
  • 1,923
  • 1,875
  • Is there any way to load them anyway? Or am I required to make a module and use the `-r` option? I also tried flattening out the code I want to use and running it in a `-e`, and even with the `-i` I end up with no prompt. – leeand00 Nov 28 '16 at 15:29
  • @leeand00: Yeah, that's what I would have used too, also being on \*nix. :-) – T.J. Crowder Nov 28 '16 at 15:38
1

You could maybe use a custom script to initiate the REPL from its module:

Something like:

const repl = require('repl'),
      path = require('path'),
      location = process.argv[2],
      base = path.basename(location),
      clean = path.split('.')[0];

const r = repl.start('> ');
Object.defineProperty(r.context, clean, {
  configurable: false,
  enumerable: true,
  value: require(location)
});

So, now you can do node loadModule /path/to/load.js, the module will be available depending on the base of the path (/path/to/load.js will be available under load for example)

MinusFour
  • 13,913
  • 3
  • 30
  • 39