3

I'd like to know if it's possible to send some to a command's stdin and then keep reading from the terminal.

The problem i'm trying to solve is executing some initialization code every time i open a Node.js REPL, so i have some functions available at the REPL from the start. Basically, to automate this:

$ node
> require('./myutils')
> ... continue using the REPL

I now i can use here string to send some text to the command's stdin:

$ node <<<"require('./myutils')"

That will execute my initialization code, but will also close the REPL immediately after that.

Maybe there's another solution for this particular problem with Node.js, but i'd look to know if there's a general way of mixing input from a string or file and then keep reading from the terminal.

Update: Chris Down's solution work, but the Node.js REPL won't run in the interactive mode by default (this is expected, as we're not reading from a terminal). Luckily, there's an -i option to force the interactive mode in the Node.js terminal:

{ echo "require('./myutils')" ; cat ; } | node -i

2 Answers 2

7
{ echo "require('./myutils')" ; cat ; } | node

Be aware that your REPL environment may act differently when taking input that's not from a terminal (for example, the prompt may not appear).

2

You can use rlwrap (wrapper for the readline library) to interact with a program whose interaction capabilities don't suit you.

rlwrap node

Rlwrap can't send initial input to the command, but it comes close: you can put some initial content in the input buffer so that you only have to press Enter.

NODE_NO_READLINE=1 rlwrap -P"require('./myutils')" node

(Setting NODE_NO_READLINE tells node not to use its built-in readline support.)

2
  • Very interesting :). Is there any particular reason you'd use NODE_NO_READLINE=1? The only difference i noticed is that when it disables the coloured output of the Node REPL. Also, it's kind of unfortunate that -P also sets -a, which in turn disables Node's TAB completion :(
    – epidemian
    Feb 16, 2013 at 10:42
  • @epidemian My solution is probably not the best one for Node. An external readline intrinsically makes it impossible to have domain-specific and especially context-sensitive completion. I posted it because it's good for some other REPLs, so it's an answer (if suboptimal) for your question and it's of interest for people who have a similar question about a different REPL and find this page in a search. Feb 17, 2013 at 9:48

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .