In python there is a nice feature, python -i
. For example, python -i myprogram.py
will run the program and then enter the interactive mode, as if I have pasted the entire program into the interactive shell.
Is there a similar command in node.js?
In python there is a nice feature, python -i
. For example, python -i myprogram.py
will run the program and then enter the interactive mode, as if I have pasted the entire program into the interactive shell.
Is there a similar command in node.js?
Docs at https://nodejs.org/api/cli.html
Preload the specified module at startup.
Follows require()'s module resolution rules. module may be either a path to a file, or a node module name.
node -i -r ./myprogram.js
Evaluate the following argument as JavaScript. The modules which are predefined in the REPL can also be used in script.
node -i -e "console.log('A message')"
These features have been added since the previous response in 2014 with the following pull requests.
I think that the node executable does not allow that you combine the -i
with any other file argument.
This is probably not the solution you would like to read. However, this worked for me. There is module called REPL that basically let you do that manually. So, I realized that I could create a wrapper around any file, as follows:
#!/bin/bash
COMMAND=$(cat <<EOF
(function(){
var repl = require('repl');
process.stdin.push('.load ${1}\n');
repl.start({
useGlobal:true,
ignoreUndefined:true,
prompt:'> '
});
})();
EOF
)
node -e "${COMMAND}"
Supposing you call this script nodejs
, then I can call this script doing something like
nodejs ./demo.js
It starts the REPL programmatically and loads your script into it. This would be equivalent to opening a REPL session manually and then run the command .load <file>
.
It is unfortunate that node has no builtin solution for this. As mentioned by here, you can preload modules with the -r
option, but you still can't access them from the REPL, making it a bit useless.
So far the best workaround I've found is to do
cat ./test.js - | node -i
Where test.js is the file you want to run. This sends it over stdin, as if you had typed in the file yourself and then waits for additional input. One downside is that it will echo the file and the result of each line back to you in the command prompt.
you can enter nodeJS then use .load /path/file.js command to import the file into current node js program
use repl
to get an interactive shell.
prepare your script:
mkdir nodesh
cd nodesh
npm init -y
npm i --save lodash repl
cat >index.js << EOF
let repl = require("repl")
let r = repl.start("node> ")
Object.defineProperty(r.context, '_', {
configurable: false,
enumerable: true,
value: require('lodash'),
})
r.context.myfn = () => {
console.log('ok')
}
EOF
cd ..
use it like this:
node nodesh/index.js
check my screenshot: