有没有一种方法可以在Node.js shell内运行JavaScript文件?

6

我刚接触Node.js,我想知道有没有一种方法可以在Node shell内部执行JavaScript文件。让我这样解释:

不是这样做:

$ node file.js

它会执行脚本,但之后会关闭Node shell...

有没有一种方法可以在Node shell内部执行脚本?类似于这样:

$ node
> file.js                  # We're now inside the Node.js shell

... script execution...

>                          # already inside the shell, 
                           # then being able to access to script variables

1
也许这个链接会有帮助:https://dev59.com/IGoy5IYBdhLWcg3wnfci - jpw
@jpw 非常有帮助!谢谢;-) - charliebrownie
2个回答

12

Node.js Shell 中执行以下命令可解决问题:

.load foo.js

2

请执行 require 操作!

示例:file.js:

console.log( "SCRIPT RUNNING" );
module.exports = "optional return";

从 shell 中要求它

$ node
> myresult = require( "./file.js" )
SCRIPT RUNNING
'optional return'
>

1
.load 将文件直接加载到 REPL 中。请参阅文档:http://nodejs.org/api/repl.html#repl_repl_features - mpneuried

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接