从命令行运行 Node.js 脚本
¥Run Node.js scripts from the command line
运行 Node.js 程序的通常方法是运行全局可用的 node
命令(安装 Node.js 后)并传递要执行的文件的名称。
¥The usual way to run a Node.js program is to run the globally available node
command (once you install Node.js) and pass the name of the file you want to execute.
如果你的主 Node.js 应用文件是 app.js
,你可以通过键入以下内容来调用它:
¥If your main Node.js application file is app.js
, you can call it by typing:
node app.js
上面,你明确告诉 shell 使用 node
运行你的脚本。你也可以使用 "shebang" 行将此信息嵌入到你的 JavaScript 文件中。"shebang" 是文件中的第一行,它告诉操作系统使用哪个解释器来运行脚本。以下是 JavaScript 的第一行:
¥Above, you are explicitly telling the shell to run your script with node
. You can also embed this information into your JavaScript file with a "shebang" line. The "shebang" is the first line in the file, and tells the OS which interpreter to use for running the script. Below is the first line of JavaScript:
#!/usr/bin/node
上面,我们明确给出了解释器的绝对路径。并非所有操作系统的 bin 文件夹中都有 node
,但所有操作系统都应该有 env
。你可以告诉操作系统以 node 作为参数运行 env
:
¥Above, we are explicitly giving the absolute path of interpreter. Not all operating systems have node
in the bin folder, but all should have env
. You can tell the OS to run env
with node as parameter:
#!/usr/bin/env node
// your javascript code
要使用 shebang,你的文件应该具有可执行权限。你可以通过运行为 app.js
授予可执行权限:
¥To use a shebang, your file should have executable permission. You can give app.js
the executable permission by running:
chmod u+x app.js
在运行命令时,请确保你位于包含 app.js
文件的同一目录中。
¥While running the command, make sure you are in the same directory which contains the app.js
file.
将字符串作为参数传递给 node
,而不是文件路径
¥Pass string as argument to node
instead of file path
要将字符串作为参数执行,你可以使用 -e
、--eval "script"
。将以下参数评估为 JavaScript。REPL 中预定义的模块也可以在脚本中使用。
¥To execute a string as argument you can use -e
, --eval "script"
. Evaluate the following argument as JavaScript. The modules which are predefined in the REPL can also be used in script.
在 Windows 上,使用 cmd.exe 单引号将无法正常工作,因为它仅识别双 "
进行引用。在 Powershell 或 Git bash 中,'
和 "
均可使用。
¥On Windows, using cmd.exe a single quote will not work correctly because it only recognizes double "
for quoting. In Powershell or Git bash, both '
and "
are usable.
node -e "console.log(123)"
自动重新启动应用
¥Restart the application automatically
从 nodejs V16 开始,有一个内置选项可以在文件更改时自动重新启动应用。这对于开发目的很有用。要使用此功能,你需要将 `--watch' 标志传递给 nodejs。
¥As of nodejs V16, there is a built-in option to automatically restart the application when a file changes. This is useful for development purposes. To use this feature, you need to pass the `--watch' flag to nodejs.
node --watch app.js
因此,当你更改文件时,应用将自动重新启动。阅读 --watch
标志文档。
¥So when you change the file, the application will restart automatically.
Read the --watch
flag documentation.