mac node repl_如何使用Node.js REPL

mac node repl

The author selected the Open Internet/Free Speech Fund to receive a donation as part of the Write for DOnations program.

作者选择了“ 开放互联网/言论自由基金会”作为“ Write for DOnations”计划的一部分来接受捐赠。

介绍 (Introduction)

The Node.js Read-Eval-Print-Loop (REPL) is an interactive shell that processes Node.js expressions. The shell reads JavaScript code the user enters, evaluates the result of interpreting the line of code, prints the result to the user, and loops until the user signals to quit.

Node.js 读取-评估-打印循环 (REPL)是处理Node.js表达式的交互式外壳。 Shell 读取用户输入JavaScript代码, 评估解释该行代码的结果,将结果打印给用户,然后循环直到用户发出退出信号。

The REPL is bundled with with every Node.js installation and allows you to quickly test and explore JavaScript code within the Node environment without having to store it in a file.

REPL与每个Node.js安装捆绑在一起,使您可以快速在Node环境中测试和浏览JavaScript代码,而不必将其存储在文件中。

先决条件 (Prerequisites)

To complete this tutorial, you will need:

要完成本教程,您将需要:

第1步-启动和停止REPL (Step 1 — Starting and Stopping the REPL)

If you have node installed, then you also have the Node.js REPL. To start it, simply enter node in your command line shell:

如果安装了node ,那么您还将拥有Node.js REPL。 要启动它,只需在命令行外壳中输入node

  • node

    节点

This results in the REPL prompt:

这将导致REPL提示符:

  • >

    >

The > symbol lets you know that you can enter JavaScript code to be immediately evaluated.

>符号使您知道可以输入要立即评估JavaScript代码。

For an example, try adding two numbers in the REPL by typing this:

例如,尝试通过输入以下内容在REPL中添加两个数字:

  • > 2 + 2

    > 2 + 2

When you press ENTER, the REPL will evaluate the expression and return:

当您按ENTER ,REPL将对表达式求值并返回:

  • 4

    4

To exit the REPL, you can type .exit, or press CTRL+D once, or press CTRL+C twice, which will return you to the shell prompt.

要退出REPL,可以键入.exit ,或按一次CTRL+D或两次按CTRL+C ,这将使您返回到shell提示符。

With starting and stopping out of the way, let’s take a look at how you can use the REPL to execute simple JavaScript code.

在开始和停止过程中,让我们看一下如何使用REPL执行简单JavaScript代码。

第2步-在Node.js REPL中执行代码 (Step 2 — Executing Code in the Node.js REPL)

The REPL is a quick way to test JavaScript code without having to create a file. Almost every valid JavaScript or Node.js expression can be executed in the REPL.

REPL是无需创建文件即可测试JavaScript代码的快速方法。 几乎每个有效JavaScript或Node.js表达式都可以在REPL中执行。

In the previous step you already tried out addition of two numbers, now let’s try division. To do so, start a new REPL:

在上一步中,您已经尝试过将两个数字相加,现在让我们尝试除法。 为此,启动一个新的REPL:

  • node

    节点

In the prompt type:

在提示符下键入:

  • > 10 / 5

    > 10/5

Press ENTER , and the output will be 2, as expected:

ENTER ,输出将为2 ,如预期的那样:

  • 2

    2

The REPL can also process operations on strings. Concatenate the following strings in your REPL by typing:

REPL还可以处理字符串操作。 通过键入以下内容以在REPL中连接以下字符串:

  • > "Hello " + "World"

    >“您好” +“世界”

Again, press ENTER, and the string expression is evaluated:

再次按ENTER ,然后对字符串表达式求值:

  • 'Hello World'

    '你好,世界'

Note: You may have noticed that the output used single quotes instead of double quotes. In JavaScript, the quotes used for a string do not affect its value. If the string you entered used a single quote, the REPL is smart enough to use double quotes in the output.

注意 :您可能已经注意到输出使用单引号而不是双引号。 在JavaScript中,用于字符串的引号不会影响其值。 如果您输入的字符串使用单引号,则REPL足够聪明,可以在输出中使用双引号。

调用函数 (Calling Functions)

When writing Node.js code, it’s common to print messages via the global console.log method or a similar function. Type the following at the prompt:

编写Node.js代码时,通常是通过全局console.log方法或类似函数来打印消息。 在提示符下键入以下内容:

  • > console.log("Hi")

    > console.log(“嗨”)

Pressing ENTER yields the following output:

ENTER产生以下输出:

  • Hi

    你好
  • undefined

    未定义

The first result is the output from console.log, which prints a message to the stdout stream (the screen). Because console.log prints a string instead of returning a string, the message is seen without quotes. The undefined is the return value of the function.

第一个结果是console.log的输出,该输出将消息stdoutstdout流(屏幕)。 因为console.log打印一个字符串而不是返回一个字符串,所以该消息没有引号。 undefined是函数的返回值。

创建变量 (Creating Variables)

Rarely do you just work with literals in JavaScript. Creating a variable in the REPL works in the same fashion as working with .js files. Type the following at the prompt:

您很少只使用JavaScript中的文字。 在REPL中创建变量的方式与处理.js文件的方式相同。 在提示符下键入以下内容:

  • > let age = 30

    >让年龄= 30

Pressing ENTER results in:

ENTER导致:

  • undefined

    未定义

Like before, with console.log, the return value of this command is undefined. The age variable will be available until you exit the REPL session. For example, you can multiply age by two. Type the following at the prompt and press ENTER:

像以前一样,使用console.log ,此命令的返回值是undefinedage变量将一直可用,直到您退出REPL会话。 例如,您可以将age乘以2。 在提示符下键入以下内容,然后按ENTER

  • > age * 2

    >年龄* 2

The result is:

结果是:

  • 60

    60

Because the REPL returns values, you don’t need to use console.log or similar functions to see the output on the screen. By default, any returned value will appear on the screen.

由于REPL返回值,因此您无需使用console.log或类似函数即可在屏幕上查看输出。 默认情况下,任何返回的值都会出现在屏幕上。

多行块 (Multi-line Blocks)

Multi-line blocks of code are supported as well. For example, you can create a function that adds 3 to a given number. Start the function by typing the following:

也支持多行代码块。 例如,您可以创建一个将给定数字加3的函数。 通过键入以下命令来启动该功能:

  • > const add3 = (num) => {

    > const add3 =(num)=> {

Then, pressing ENTER will change the prompt to:

然后,按ENTER将提示更改为:

  • ...

    ...

The REPL noticed an open curly bracket and therefore assumes you’re writing more than one line of code, which needs to be indented. To make it easier to read, the REPL adds 3 dots and a space on the next line, so the following code appears to be indented.

REPL注意到一个大括号,因此假定您正在编写多行代码,需要缩进一行。 为了便于阅读,REPL在下一行添加了3个点和一个空格,因此以下代码似乎是缩进的。

Enter the second and third lines of the function, one at a time, pressing ENTER after each:

输入函数的第二行和第三行,一次输入一次,每行之后按ENTER

  • ... return num + 3;

    ...返回num + 3;
  • ... }

    ...}

Pressing ENTER after the closing curly bracket will display an undefined, which is the “return value” of the function assignment to a variable. The ... prompt is now gone and the > prompt returns:

在右花括号后按ENTER将显示一个undefined ,它是函数分配给变量的“返回值”。 ...提示现在消失了, >提示返回:

undefined
>

Now, call add3() on a value:

现在,对一个值调用add3()

  • > add3(10)

    > add3(10)

As expected, the output is:

如预期的那样,输出为:

  • 13

    13

You can use the REPL to try out bits of JavaScript code before including them into your programs. The REPL also includes some handy shortcuts to make that process easier.

您可以使用REPL在将JavaScript代码包含到程序中之前先对其进行尝试。 REPL还包括一些方便的快捷方式,以使该过程更容易。

第3步-掌握REPL快捷方式 (Step 3 — Mastering REPL Shortcuts)

The REPL provides shortcuts to decrease coding time when possible. It keeps a history of all the entered commands and allows us to cycle through them and repeat a command if necessary.

REPL提供了缩短编码时间的捷径。 它保留了所有输入命令的历史记录,并允许我们循环浏览它们,并在必要时重复一条命令。

For an example, enter the following string:

例如,输入以下字符串:

  • "The answer to life the universe and everything is 32"

    “宇宙和一切生命的答案是32”

This results in:

结果是:

'The answer to life the universe and everything is 32'

If we’d like to edit the string and change the “32” to “42”, at the prompt, use the UP arrow key to return to the previous command:

如果我们要编辑字符串并将“ 32”更改为“ 42”,请在提示符下使用UP箭头键返回上一个命令:

> "The answer to life the universe and everything is 32"

Move the cursor to the left, delete 3, enter 4, and press ENTER again:

将光标向左移动,删除3 ,输入4 ,然后再次按ENTER

'The answer to life the universe and everything is 42'

Continue to press the UP arrow key, and you’ll go further back through your history until the first used command in the current REPL session. In contrast, pressing DOWN will iterate towards the more recent commands in the history.

继续按UP箭头键,您将进一步追溯历史,直到当前REPL会话中的第一个使用的命令。 相比之下,按下DOWN将迭代历史记录中的最新命令。

When you are done maneuvering through your command history, press DOWN repeatedly until you have exhausted your recent command history and are once again seeing the prompt.

完成命令历史记录的操作后,请反复按DOWN ,直到您用完了最近的命令历史记录并再次看到提示。

To quickly get the last evaluated value, use the underscore character. At the prompt, type _ and press ENTER:

要快速获取上一个评估值,请使用下划线字符。 在提示符下,键入_并按ENTER

  • > _

    > _

The previously entered string will appear again:

先前输入的字符串将再次出现:

'The answer to life the universe and everything is 42'

The REPL also has an autocompletion for functions, variables, and keywords. If you wanted to find the square root of a number using the Math.sqrt function, enter the first few letters, like so:

REPL还具有对函数,变量和关键字的自动补全功能。 如果要使用Math.sqrt函数查找数字的平方根,请输入前几个字母,如下所示:

  • > Math.sq

    > Math.sq

Then press the TAB key and the REPL will autocomplete the function:

然后按TAB键,REPL将自动完成该功能:

> Math.sqrt

When there are multiple possibilities for autocompletion, you’re prompted with all the available options. For an example, enter just:

如果存在自动完成的多种可能性,则会提示您所有可用选项。 例如,输入:

  • > Math.

    >数学。

And press TAB twice. You’re greeted with the possible autocompletions:

然后按两次TAB键。 您可能会遇到自动完成的问题:

> Math.
Math.__defineGetter__      Math.__defineSetter__      Math.__lookupGetter__
Math.__lookupSetter__      Math.__proto__             Math.constructor
Math.hasOwnProperty        Math.isPrototypeOf         Math.propertyIsEnumerable
Math.toLocaleString        Math.toString              Math.valueOf

Math.E                     Math.LN10                  Math.LN2
Math.LOG10E                Math.LOG2E                 Math.PI
Math.SQRT1_2               Math.SQRT2                 Math.abs
Math.acos                  Math.acosh                 Math.asin
Math.asinh                 Math.atan                  Math.atan2
Math.atanh                 Math.cbrt                  Math.ceil
Math.clz32                 Math.cos                   Math.cosh
Math.exp                   Math.expm1                 Math.floor
Math.fround                Math.hypot                 Math.imul
Math.log                   Math.log10                 Math.log1p
Math.log2                  Math.max                   Math.min
Math.pow                   Math.random                Math.round
Math.sign                  Math.sin                   Math.sinh
Math.sqrt                  Math.tan                   Math.tanh
Math.trunc

Depending on the screen size of your shell, the output may be displayed with a different number of rows and columns. This is a list of all the functions and properties that are available in the Math module.

根据外壳的屏幕尺寸,输出可能显示为不同数量的行和列。 这是“ Math模块中所有可用功能和属性的列表。

Press CTRL+C to get to a new line in the prompt without executing what is in the current line.

在不执行当前行内容的情况下,按CTRL+C进入提示中的新行。

Knowing the REPL shortcuts makes you more efficient when using it. Though, there’s another thing REPL provides for increased productivity—The REPL commands.

了解REPL快捷方式可以使您更高效地使用它。 但是,REPL还提供了另一项提高生产率的功能-REPL命令

步骤4 —使用REPL命令 (Step 4 — Using REPL Commands)

The REPL has specific keywords to help control its behavior. Each command begins with a dot ..

REPL具有特定的关键字来帮助控制其行为。 每个命令都以点开头.

。救命 (.help)

To list all the available commands, use the .help command:

要列出所有可用命令,请使用.help命令:

  • > .help

    > .help

There aren’t many, but they’re useful for getting things done in the REPL:

并没有很多,但是它们对于在REPL中完成工作很有用:

.break    Sometimes you get stuck, this gets you out
.clear    Alias for .break
.editor   Enter editor mode
.exit     Exit the repl
.help     Print this help message
.load     Load JS from a file into the REPL session
.save     Save all evaluated commands in this REPL session to a file

Press ^C to abort current expression, ^D to exit the repl

If ever you forget a command, you can always refer to .help to see what it does.

如果忘记了命令,则始终可以参考.help来查看其功能。

.break / .clear (.break/.clear)

Using .break or .clear, it’s easy to exit a multi-line expression. For example, begin a for loop as follows:

使用.break.clear ,很容易退出多行表达式。 例如,开始如下所示的for loop

  • > for (let i = 0; i < 100000000; i++) {

    > for(让i = 0; i <100000000; i ++){

To exit from entering any more lines, instead of entering the next one, use the .break or .clear command to break out:

要退出任何更多行,而不是输入下一行,请使用.break.clear命令进行拆分:

  • ... .break

    ....休息

You’ll see a new prompt:

您会看到一个新提示:

>

The REPL will move on to a new line without executing any code, similar to pressing CTRL+C.

REPL将继续执行新行而不执行任何代码,类似于按CTRL+C

.save和.load (.save and .load)

The .save command stores all the code you ran since starting the REPL, into a file. The .load command runs all the JavaScript code from a file inside the REPL.

.save命令将自启动REPL以来运行的所有代码存储到文件中。 .load命令从REPL内的文件运行所有JavaScript代码。

Quit the session using the .exit command or with the CTRL+D shortcut. Now start a new REPL with node. Now only the code you are about to write will be saved.

使用.exit命令或CTRL+D快捷方式退出会话。 现在,使用node启动一个新的REPL。 现在,只有要编写的代码将被保存。

Create an array with fruits:

用水果创建一个数组:

  • > fruits = ['banana', 'apple', 'mango']

    >水果= ['香蕉','苹果','芒果']

In the next line, the REPL will display:

在下一行中,REPL将显示:

[ 'banana', 'apple', 'mango' ]

Save this variable to a new file, fruits.js:

将此变量保存到一个新文件fruits.js

  • > .save fruits.js

    > .savefruit.js

We’re greeted with the confirmation:

我们得到了确认:

Session saved to: fruits.js

The file is saved in the same directory where you opened the Node.js REPL. For example, if you opened the Node.js REPL in your home directory, then your file will be saved in your home directory.

该文件保存在打开Node.js REPL的目录中。 例如,如果您在主目录中打开Node.js REPL,则文件将保存在主目录中。

Exit the session and start a new REPL with node. At the prompt, load the fruits.js file by entering:

退出会话,并使用node启动新的REPL。 在提示符下,通过输入以下内容来加载fruits.js文件:

  • > .load fruits.js

    > .load fruit.js

This results in:

结果是:

fruits = ['banana', 'apple', 'mango']

[ 'banana', 'apple', 'mango' ]

The .load command reads each line of code and executes it, as expected of a JavaScript interpreter. You can now use the fruits variable as if it was available in the current session all the time.

.load命令按照JavaScript解释器的预期读取并执行每一行代码。 现在,您可以使用fruits变量,就好像它始终在当前会话中可用。

Type the following command and press ENTER:

键入以下命令,然后按ENTER

  • > fruits[1]

    >水果[1]

The REPL will output:

REPL将输出:

'apple'

You can load any JavaScript file with the .load command, not only items you saved. Let’s quickly demonstrate by opening your preferred code editor or nano, a command line editor, and create a new file called peanuts.js:

您可以使用.load命令加载任何JavaScript文件,而不仅限于保存的项目。 让我们通过打开您喜欢的代码编辑器或命令行编辑器nano快速演示,并创建一个新的文件peanuts.js

  • nano peanuts.js

    纳米花生.js

Now that the file is open, type the following:

现在,文件已打开,键入以下内容:

peanuts.js
花生.js
console.log('I love peanuts!');

Save and exit nano by pressing CTRL+X.

通过按CTRL+X保存并退出nano。

In the same directory where you saved peanuts.js, start the Node.js REPL with node. Load peanuts.js in your session:

在保存peanuts.js目录中,使用node启动Node.js REPL。 在您的会话中加载peanuts.js

  • > .load peanuts.js

    > .load花生.js

The .load command will execute the single console statement and display the following output:

.load命令将执行单个console语句并显示以下输出:

console.log('I love peanuts!');

I love peanuts!
undefined
>

When your REPL usage goes longer than expected, or you believe you have an interesting code snippet worth sharing or explore in more depth, you can use the .save and .load commands to make both those goals possible.

当REPL的使用时间比预期的长,或者您认为自己有一个有趣的代码段值得共享或更深入地研究时,可以使用.save.load命令使这两个目标都实现。

结论 (Conclusion)

The REPL is an interactive environment that allows you to execute JavaScript code without first having to write it to a file.

REPL是一个交互式环境,使您无需先将JavaScript代码写入文件即可执行JavaScript代码。

You can use the REPL to try out JavaScript code from other tutorials:

您可以使用REPL尝试其他教程中JavaScript代码:

翻译自: https://www.digitalocean.com/community/tutorials/how-to-use-the-node-js-repl

mac node repl

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值