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:
Using a shebang line
You can embed interpreter information directly 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.node in the bin folder, but all should have env. You can tell the OS to run env with node as a parameter:
app.js executable permission by running:
When running the command, make sure you are in the same directory that contains the
app.js file.Pass a string as argument to node instead of a file path
To execute a string as an argument, use -e / --eval "script". This evaluates the argument as JavaScript. Modules that are predefined in the REPL can also be used in the script.
Restart the application automatically
As of Node.js v16, there is a built-in option to automatically restart the application when a file changes. This is useful for development purposes. Pass the--watch flag to Node.js:
--watch flag documentation for more details.
Run a task with Node.js
Node.js provides a built-in task runner that allows you to execute specific commands defined in yourpackage.json file. This is useful for automating repetitive tasks such as running tests, building your project, or linting your code.
Using the --run flag
The --run flag allows you to run a specified command from the scripts section of your package.json. For example, given the following package.json:
test script using the --run flag:
Passing arguments to the command
Thedev key in the scripts object above uses the -- --another-argument syntax to pass arguments to the command. In this case, --watch is passed to the dev script:
Environment variables
The--run flag sets specific environment variables that can be useful for your scripts:
NODE_RUN_SCRIPT_NAME: The name of the script being run.NODE_RUN_PACKAGE_JSON_PATH: The path to thepackage.jsonfile being processed.
Intentional limitations
The Node.js task runner is intentionally more limited compared to other task runners like
npm run or yarn run. It focuses on performance and simplicity, omitting features like running pre or post scripts. This makes it suitable for straightforward tasks but may not cover all use cases.