
How to Launch Node.JS scripts from the Terminal
In this page, we will learn to execute JavaScript files and code through the command line or the bash terminal
First , open your command line window. Here, I’m using the Windows Command Prompt. An alternative to the Windows Command Prompt is also Git Bash
To execute a single JavaScript line, you can use the command :
node -e " <command> " An example can be:
node -e " console.log('Hello World') " Hit the enter key, and you will see the words “Hello World” printed out on the console
Executing code from a file
To run JavaScript code from a file, you can use :
node <filename>Running code files located within the same directory as your CMD home directory
If you have a script called “myscript.js” which is located within your C:/Users/<user name> directory, you will run the command:
node myscript.jsor
node myscriptAs you can see from the above commands, including the extension does not matter. However, this rule is only applicable if myscript is the JavaScript file, not a directory
Running Code from a file from a directory that is not the same as your CMD home directory
To run from parent directory
node ../myscript.jsTo run from other directory relative to CMD home directory
To run file myscript located in C:/Users/<User name>/myfolder
node ./myfolder/myscript.jsTo run from an entirely different directory
Let’s say you want to run myscript.js from E:/nodejs/
node E:/nodejs/myscript.jsIn the next article, we will dive deeper into the Node.JS engine to write scripts through utilization of modules and exports.
All of the commands listed above are the ways you can run NodeJS scripts directly from the command line. Thank you so much for reading!
Stay home, Stay safe