javascriptnode.jscommand-line-interfaceread-eval-print-loop

Undefined function in node.js REPL session from js file


I have a test js script to load into REPL session:

// testRepl.js
const cls = () => console.clear();
const msg = txt => console.info(txt);
const ajax = url => msg(url);

I am loading this file in REPL using the following command

> node
> .load .testRepl.js

The problem is that REPL session can load cls and msg functions, but is unable to identify ajax, as displayed in the following image:

ajax is is unidentified

So this works:

> cls()
> msg("Hello")

But this fails:

> ajax("Hello World!")

EDIT

This is the code exactly in my testRepl.js:

enter image description here


Solution

  • Maybe you don't have a newline at the end of your .js file or something, because trying to reproduce the issue it all works for me:

    $ cat /tmp/foo.js
    const cls = () => console.clear();
    const msg = txt => console.info(txt);
    const ajax = url => msg(url);
    
    $ node
    Welcome to Node.js v16.16.0.
    Type ".help" for more information.
    > .load /tmp/foo.js
    const cls = () => console.clear();
    const msg = txt => console.info(txt);
    const ajax = url => msg(url);
    
    undefined
    > ajax
    [Function: ajax]
    

    Tried in node v16, v18 and v20. All the same results.