How can I make the Node REPL print the result only?

I want to run a script using .load myFile.js but I dont want to print everything that is in the file, only the value/result of whatever is the file. I’m using Electron, xterm.js, and node-pty for my project.

For example, with this code:

// type your code here

function sum(x, y) {
  return x + y
}

sum(2, 3)

I get something like this:

> // type your code here
undefined
> function sum(x, y) {
...   return x + y
... }
undefined
> sum(2, 3)
5
>

Answer

If you’re okay with the code running inside the current scope, just eval it:

> eval(fs.readFileSync('myFile.js', 'utf8'))
5

If you want a new scope, vm.runInNewContext (this is not a security thing, only scope cleanliness):

> vm.runInNewContext(fs.readFileSync('myFile.js', 'utf8'))
5

Globals like require can be passed in its second argument.