Search code examples
node.jsread-eval-print-loop

How to use Node.js repl with file as input


I wish to use a js file input as node.js repl, as if it was a command line code: node -e '<my code>', but with a <filename> instead of an inline code.

How can this be done as the file name as an input, without needing to use another file (such as fs.readFileSync(..))


Solution

  • One way is to use the REPL's .load command and Node's -i flag.

    echo ".load test.js" | node -i
    

    Outputs:

    $ echo ".load test.js" | node -i 
    Welcome to Node.js v12.8.1.
    Type ".help" for more information.
    > .load test.js
    2 + 2;
    
    4