从命令行运行 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.
If your main Node.js application file is
app.js, you can call it by typing:
Above, you are explicitly telling the shell to run your script with
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:
To use a shebang, your file should have executable permission. You can give
app.js the executable permission by running:
While running the command, make sure you are in the same directory which contains the
To execute a string as argument you can use
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
" are usable.
node command has to be re-executed in bash whenever there is a change in the application. To restart the application automatically, use the
Install the nodemon module globally to system path:
You can also install nodemon as a development dependency:
This local installation of nodemon can be run by calling it from within npm script such as npm start or using npx nodemon.
Run the application using the
nodemon command followed by the application's file name: