0

What I want is very simple, to run code while typing, just like enter node and run things like this:

% node
Welcome to Node.js v17.0.1.
Type ".help" for more information.
> var a=5; var b=6;
> console.log(a+b);
11

But in this case, I have to copy and paste my code again and again.

Is it possible to "include" the code from an eternal .js file, then let me stay in the console-like environment to run the code?

Store these in the app.js:

var a=5;
var b=6;
function addNumber(x,y){console.log(x+y);}

In node console:

% node
Welcome to Node.js v17.0.1.
Type ".help" for more information.
> include "app.js" //- This is what I'm looking for
> addNumber(a,b);
11

1 Answer 1

3

You can require files in the REPL just as easily as you can in a standard Node script.

For example, inside a directory, create a file, foo.js:

module.exports = () => 'foo';

And inside that directory, enter Node:

PS D:\Directory> node
Welcome to Node.js v14.17.6.
Type ".help" for more information.
> const foo = require('./foo');
undefined
> console.log(foo())
foo
undefined
>

require('./foo') will return the exports of the foo file in the same directory.

require('../foo') will return the exports of the foo file in the parent directory.

Absolute paths work too. And so on.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.