如何将脚本加载到节点中。js REPL吗?

时间:2021-09-09 15:02:27

I have a script foo.js that contains some functions I want to play with in the REPL.

我有一个脚本foo。它包含一些我想在REPL中使用的函数。

Is there a way to have node execute my script and then jump into a REPL with all the declared globals, like I can with python -i foo.py or ghci foo.hs?

是否有一种方法可以让node执行我的脚本,然后用所有已声明的全局变量(比如我可以使用python -i - foo)跳转到一个REPL。py或ghci foo。?

10 个解决方案

#1


127  

There is still nothing built-in to provide the exact functionality you describe. However, an alternative to using require it to use the .load command within the REPL, like such:

仍然没有任何内置功能提供您所描述的精确功能。但是,另一种使用方法要求它在REPL中使用.load命令,如下所示:

.load foo.js

It loads the file in line by line just as if you had typed it in the REPL. Unlike require this pollutes the REPL history with the commands you loaded. However, it has the advantage of being repeatable because it is not cached like require.

它按一行按一行加载文件,就像在REPL中键入它一样。与require不同的是,它会用加载的命令污染REPL历史。但是,它具有可重复的优点,因为它不像require那样缓存。

Which is better for you will depend on your use case.

哪种方式更适合您将取决于您的用例。


Edit: It has limited applicability because it does not work in strict mode, but three years later I have learned that if your script does not have 'use strict', you can use eval to load your script without polluting the REPL history:

编辑:它的适用性有限,因为它没有在严格模式下工作,但是三年后我了解到,如果您的脚本没有“使用严格”,您可以使用eval来加载您的脚本,而不会污染REPL历史:

var fs = require('fs');
eval(fs.readFileSync('foo.js').toString())

#2


7  

I created replpad since I got tired of reloading the script repeatedly.

我创建了replpad,因为我厌倦了反复重载脚本。

Simply install it via: npm install -g replpad

只需通过:npm安装-g回复板

Then use it by running: replpad

然后运行:replpad来使用它

If you want it to watch all files in the current and all subdirectories and pipe them into the repl when they change do: replpad .

如果您想让它监视当前和所有子目录中的所有文件,并在它们更改时将它们导入repl: replpad。

Check out the videos on the site to get a better idea of how it works and learn about some other nice features that it has like these:

看看网站上的视频,更好地了解它是如何工作的,并了解它拥有的其他一些不错的功能,比如:

  • access core module docs in the repl via the dox() function that is added to every core function, i.e. fs.readdir.dox()
  • 在repl中通过dox()函数访问核心模块文档,该函数被添加到每个核心函数中,即fs.readdir.dox()
  • access user module readmes in the repl via the dox() function that is added to every module installed via npm, i.e. marked.dox()
  • 通过dox()函数访问repl中的用户模块readmes,该函数被添加到通过npm安装的每个模块中,即marked.dox()
  • access function's highlighted source code, info on where function was defined (file, linenumber) and function comments and/or jsdocs where possible via the src property that is added to every function, i.e. express.logger.src
  • 访问函数突出显示的源代码,关于函数定义位置的信息(文件、linenumber)以及函数注释和/或jsdocs(如果可能的话),可以通过src属性添加到每个函数中,例如express.logger.src
  • scriptie-talkie support (see .talk command)
  • 脚本支持(参见.talk命令)
  • adds commands and keyboard shortcuts
  • 添加命令和键盘快捷键。
  • vim key bindings
  • vim键绑定
  • key map support
  • 键映射支持
  • parens matching via match token plugin
  • 通过匹配令牌插件进行配对
  • appends code entered in repl back to file via keyboard shortcut or .append command
  • 通过键盘快捷键或.append命令将代码输入到repl中。

#3


7  

I made Vorpal.js, which handles this problem by turning your node add into an interactive CLI. It supports a REPL extension, which drops you into a REPL within the context of your running app.

我做了类别。js,通过将节点添加到交互式CLI中来处理这个问题。它支持一个REPL扩展,它将您放入正在运行的应用程序上下文中的REPL中。

var vorpal = require('vorpal')();
var repl = require('vorpal-repl');

vorpal
  .delimiter('myapp>')
  .use(repl)
  .show()
  .parse(process.argv); 

Then you can run the app and it will drop into a REPL.

然后你可以运行这个应用程序,它会进入一个REPL。

$ node myapp.js repl
myapp> repl: 

#4


6  

i always use this command

我总是使用这个命令

node -i -e "$(< yourScript.js)"

works exactly as in Python without any packages.

与Python中没有任何包的情况完全相同。

#5


4  

Currently you can't do that directly, but you can mylib = require('./foo.js') in the REPL. Remember methods are exported, not declared as globals.

目前您不能直接这样做,但是可以在REPL中使用mylib = require('./foo.js')。记住方法是导出的,而不是声明为全局变量。

#6


3  

replpad is cool, but for a quick and easy way to load a file into node, import its variables and start a repl, you can add the following code to the end of your .js file

replpad很酷,但是要将文件加载到node、导入其变量并启动repl,您可以在.js文件的末尾添加以下代码

if (require.main === module){
    (function() {
        var _context = require('repl').start({prompt: '$> '}).context;
        var scope = require('lexical-scope')(require('fs').readFileSync(__filename));
        for (var name in scope.locals[''] )
            _context[scope.locals[''][name]] = eval(scope.locals[''][name]);
        for (name in scope.globals.exported)
            _context[scope.globals.exported[name]] = eval(scope.globals.exported[name]);
    })();
}

Now if your file is src.js, running node src.js will start node, load the file, start a REPL, and copy all the objects declared as var at the top level as well as any exported globals. The if (require.main === module) ensures that this code will not be executed if src.js is included through a require statement. I fact, you can add any code you want to be excuted when you are running src.js standalone for debugging purposes inside the if statement.

如果你的文件是src。js,src节点运行。js将启动节点、加载文件、启动REPL并复制顶层声明为var的所有对象以及任何导出的全局变量。如果需要。main === = module)确保如果src,此代码不会被执行。js通过require语句包含。事实上,您可以在运行src时添加任何想要执行的代码。js独立于if语句中的调试目的。

#7


3  

Another way is to define those functions as global.

另一种方法是将这些函数定义为全局函数。

global.helloWorld = function() { console.log("Hello World"); }

Then preload the file in the REPL as:

然后将REPL中的文件预加载为:

node -r ./file.js

Then the function helloWorld can be accessed directly in the REPL.

然后,可以直接在REPL中访问函数helloWorld。

#8


2  

Another suggestion that I do not see here: try this little bit of code

另一个我在这里没有看到的建议是:尝试这一小段代码

#!/usr/bin/env node
'use strict';

const repl = require('repl');
const cli = repl.start({ replMode: repl.REPL_MODE_STRICT });
cli.context.foo = require('./foo'); // injects it into the repl

Then you can simply run this script and it will include foo as a variable

然后您可以简单地运行这个脚本,它将包括foo作为一个变量。

#9


2  

Why not load the file into an interactive node repl?

为什么不将文件加载到交互式节点repl中呢?

node -h
-e, --eval script          evaluate script
-i, --interactive          always enter the REPL even if stdin

node -e 'var client = require("./build/main/index.js"); console.log("Use `client` in repl")' -i

Then you can add to package.json scripts

然后可以添加到package。json脚本

"repl": "node -e 'var client = require(\"./build/main/index.js\"); console.log(\"Use `client` in repl\")' -i",

tested using node v8.1.2

测试使用节点v8.1.2中

#10


0  

Here's a bash function version of George's answer:

下面是George的一个bash函数版本:

noderepl() {
    FILE_CONTENTS="$(< $1 )"
    node -i -e "$FILE_CONTENTS"
}

If you put this in your ~/.bash_profile you can use it like an alias, i.e.:

如果你把这个放在你的信封里。bash_profile可以将其用作别名,例如:

noderepl foo.js

#1


127  

There is still nothing built-in to provide the exact functionality you describe. However, an alternative to using require it to use the .load command within the REPL, like such:

仍然没有任何内置功能提供您所描述的精确功能。但是,另一种使用方法要求它在REPL中使用.load命令,如下所示:

.load foo.js

It loads the file in line by line just as if you had typed it in the REPL. Unlike require this pollutes the REPL history with the commands you loaded. However, it has the advantage of being repeatable because it is not cached like require.

它按一行按一行加载文件,就像在REPL中键入它一样。与require不同的是,它会用加载的命令污染REPL历史。但是,它具有可重复的优点,因为它不像require那样缓存。

Which is better for you will depend on your use case.

哪种方式更适合您将取决于您的用例。


Edit: It has limited applicability because it does not work in strict mode, but three years later I have learned that if your script does not have 'use strict', you can use eval to load your script without polluting the REPL history:

编辑:它的适用性有限,因为它没有在严格模式下工作,但是三年后我了解到,如果您的脚本没有“使用严格”,您可以使用eval来加载您的脚本,而不会污染REPL历史:

var fs = require('fs');
eval(fs.readFileSync('foo.js').toString())

#2


7  

I created replpad since I got tired of reloading the script repeatedly.

我创建了replpad,因为我厌倦了反复重载脚本。

Simply install it via: npm install -g replpad

只需通过:npm安装-g回复板

Then use it by running: replpad

然后运行:replpad来使用它

If you want it to watch all files in the current and all subdirectories and pipe them into the repl when they change do: replpad .

如果您想让它监视当前和所有子目录中的所有文件,并在它们更改时将它们导入repl: replpad。

Check out the videos on the site to get a better idea of how it works and learn about some other nice features that it has like these:

看看网站上的视频,更好地了解它是如何工作的,并了解它拥有的其他一些不错的功能,比如:

  • access core module docs in the repl via the dox() function that is added to every core function, i.e. fs.readdir.dox()
  • 在repl中通过dox()函数访问核心模块文档,该函数被添加到每个核心函数中,即fs.readdir.dox()
  • access user module readmes in the repl via the dox() function that is added to every module installed via npm, i.e. marked.dox()
  • 通过dox()函数访问repl中的用户模块readmes,该函数被添加到通过npm安装的每个模块中,即marked.dox()
  • access function's highlighted source code, info on where function was defined (file, linenumber) and function comments and/or jsdocs where possible via the src property that is added to every function, i.e. express.logger.src
  • 访问函数突出显示的源代码,关于函数定义位置的信息(文件、linenumber)以及函数注释和/或jsdocs(如果可能的话),可以通过src属性添加到每个函数中,例如express.logger.src
  • scriptie-talkie support (see .talk command)
  • 脚本支持(参见.talk命令)
  • adds commands and keyboard shortcuts
  • 添加命令和键盘快捷键。
  • vim key bindings
  • vim键绑定
  • key map support
  • 键映射支持
  • parens matching via match token plugin
  • 通过匹配令牌插件进行配对
  • appends code entered in repl back to file via keyboard shortcut or .append command
  • 通过键盘快捷键或.append命令将代码输入到repl中。

#3


7  

I made Vorpal.js, which handles this problem by turning your node add into an interactive CLI. It supports a REPL extension, which drops you into a REPL within the context of your running app.

我做了类别。js,通过将节点添加到交互式CLI中来处理这个问题。它支持一个REPL扩展,它将您放入正在运行的应用程序上下文中的REPL中。

var vorpal = require('vorpal')();
var repl = require('vorpal-repl');

vorpal
  .delimiter('myapp>')
  .use(repl)
  .show()
  .parse(process.argv); 

Then you can run the app and it will drop into a REPL.

然后你可以运行这个应用程序,它会进入一个REPL。

$ node myapp.js repl
myapp> repl: 

#4


6  

i always use this command

我总是使用这个命令

node -i -e "$(< yourScript.js)"

works exactly as in Python without any packages.

与Python中没有任何包的情况完全相同。

#5


4  

Currently you can't do that directly, but you can mylib = require('./foo.js') in the REPL. Remember methods are exported, not declared as globals.

目前您不能直接这样做,但是可以在REPL中使用mylib = require('./foo.js')。记住方法是导出的,而不是声明为全局变量。

#6


3  

replpad is cool, but for a quick and easy way to load a file into node, import its variables and start a repl, you can add the following code to the end of your .js file

replpad很酷,但是要将文件加载到node、导入其变量并启动repl,您可以在.js文件的末尾添加以下代码

if (require.main === module){
    (function() {
        var _context = require('repl').start({prompt: '$> '}).context;
        var scope = require('lexical-scope')(require('fs').readFileSync(__filename));
        for (var name in scope.locals[''] )
            _context[scope.locals[''][name]] = eval(scope.locals[''][name]);
        for (name in scope.globals.exported)
            _context[scope.globals.exported[name]] = eval(scope.globals.exported[name]);
    })();
}

Now if your file is src.js, running node src.js will start node, load the file, start a REPL, and copy all the objects declared as var at the top level as well as any exported globals. The if (require.main === module) ensures that this code will not be executed if src.js is included through a require statement. I fact, you can add any code you want to be excuted when you are running src.js standalone for debugging purposes inside the if statement.

如果你的文件是src。js,src节点运行。js将启动节点、加载文件、启动REPL并复制顶层声明为var的所有对象以及任何导出的全局变量。如果需要。main === = module)确保如果src,此代码不会被执行。js通过require语句包含。事实上,您可以在运行src时添加任何想要执行的代码。js独立于if语句中的调试目的。

#7


3  

Another way is to define those functions as global.

另一种方法是将这些函数定义为全局函数。

global.helloWorld = function() { console.log("Hello World"); }

Then preload the file in the REPL as:

然后将REPL中的文件预加载为:

node -r ./file.js

Then the function helloWorld can be accessed directly in the REPL.

然后,可以直接在REPL中访问函数helloWorld。

#8


2  

Another suggestion that I do not see here: try this little bit of code

另一个我在这里没有看到的建议是:尝试这一小段代码

#!/usr/bin/env node
'use strict';

const repl = require('repl');
const cli = repl.start({ replMode: repl.REPL_MODE_STRICT });
cli.context.foo = require('./foo'); // injects it into the repl

Then you can simply run this script and it will include foo as a variable

然后您可以简单地运行这个脚本,它将包括foo作为一个变量。

#9


2  

Why not load the file into an interactive node repl?

为什么不将文件加载到交互式节点repl中呢?

node -h
-e, --eval script          evaluate script
-i, --interactive          always enter the REPL even if stdin

node -e 'var client = require("./build/main/index.js"); console.log("Use `client` in repl")' -i

Then you can add to package.json scripts

然后可以添加到package。json脚本

"repl": "node -e 'var client = require(\"./build/main/index.js\"); console.log(\"Use `client` in repl\")' -i",

tested using node v8.1.2

测试使用节点v8.1.2中

#10


0  

Here's a bash function version of George's answer:

下面是George的一个bash函数版本:

noderepl() {
    FILE_CONTENTS="$(< $1 )"
    node -i -e "$FILE_CONTENTS"
}

If you put this in your ~/.bash_profile you can use it like an alias, i.e.:

如果你把这个放在你的信封里。bash_profile可以将其用作别名,例如:

noderepl foo.js