问题描述
在node.js中进入交互模式之前,是否有办法执行某些代码(在文件中或从字符串中,并不重要)?
Is there a way to execute some code (in a file or from a string, doesn't really matter) before dropping into interactive mode in node.js?
例如,如果我创建一个脚本 __ preamble __。js
,其中包含:
For example, if I create a script __preamble__.js
which contains:
console.log("preamble executed! poor guy!");
和用户输入节点__preamble __。js
他们得到这个输出:
and a user types node __preamble__.js
they get this output:
preamble executed! poor guy!
> [interactive mode]
推荐答案
真的很老问题但......
Really old question but...
我相信我正在寻找类似的东西,并发现了这一点。
您可以打开REPL(在终端上键入 node
),然后加载文件。
像这样: .load ./script.js
。
按enter键,将执行文件内容。现在,脚本中创建的所有内容(对象,变量,函数)都可用。
I was looking for something similar, I believe, and found out this.You can open the REPL (typing node
on your terminal) and then load a file.Like this: .load ./script.js
.Press enter and the file content will be executed. Now everything created (object, variable, function) in your script will be available.
例如:
// script.js
var y = {
name: 'obj',
status: true
};
var x = setInterval(function () {
console.log('As time goes by...');
}, 5000);
在REPL上:
//REPL
.load ./script.js
现在,您键入REPL并与生活代码进行交互。
您可以 console.log(y)
或 clearInterval(x)
;
Now you type on the REPL and interact with the "living code".You can console.log(y)
or clearInterval(x)
;
这将有点奇怪,因为随着时间的推移......每隔五秒(或左右)继续出现。
但它会起作用!
It will be a bit odd, cause "As time goes by..." keep showing up every five seconds (or so).But it will work!
这篇关于执行一些代码,然后进入交互式节点的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!