Running JavaScript in Node.js
Learn how to create JavaScript files, execute programs using Node.js, understand terminal output, work with variables and functions, and troubleshoot common execution errors.
1. Introduction to Running JavaScript
JavaScript can run in different environments. A browser executes JavaScript for webpage interactions, while Node.js executes JavaScript outside the browser.
To run JavaScript using Node.js, we write code in a file with
the .js extension and execute that file through
the terminal. Node.js reads the file and runs its JavaScript
statements.
node filename.js runs the specified
JavaScript file. Make sure Node.js is installed and available
in your terminal before executing the command.
Ways to Execute JavaScript
| Method | How It Works | Suitable For |
|---|---|---|
| Node.js REPL | Executes expressions interactively. | Quick experiments and calculations. |
| JavaScript File | Executes code saved in a .js file. |
Programs and reusable logic. |
| npm Script | Runs a command configured in package.json. |
Project workflows and development commands. |
2. JavaScript Execution Workflow
The following diagram shows how a JavaScript file is executed using Node.js.
app.js
node app.js
If the program contains an error, Node.js may display an error message instead of completing the program successfully.
3. Create Your First JavaScript File
Let us create a simple JavaScript program that prints a welcome message for Samadhan and Pradnya.
Step 1: Create a Project Folder
Create a folder named NodeJsPractice on your
computer. Open this folder in your code editor.
Step 2: Create app.js
Inside the folder, create a file named app.js
and write the following code.
console.log("Welcome to Node.js!");
console.log("Hello Samadhan!");
console.log("Hello Pradnya!");
console.log("Welcome to CIIT TRAINING INSTITUTE.");
Step 3: Save the File
Save the file with the exact name app.js.
Ensure that the file is not accidentally saved as
app.js.txt.
Expected Project Structure
NodeJsPractice/
└── app.js
4. Execute JavaScript Using Node.js
After creating and saving the file, execute it from the terminal.
Step 1: Open the Terminal
Open the terminal in the NodeJsPractice folder.
You can use your code editor's integrated terminal or Command Prompt.
Step 2: Run the Command
node app.js
Expected Output
Welcome to Node.js!
Hello Samadhan!
Hello Pradnya!
Welcome to CIIT TRAINING INSTITUTE.
Command Explanation
nodestarts the Node.js runtime.app.jsspecifies the JavaScript file to execute.console.log()prints each message to the terminal.
app.js, or provide the correct relative path
to the file.
5. Run JavaScript with Variables
JavaScript files can contain variables, calculations, conditions, loops, and functions. Node.js executes these statements in order, subject to the program's control flow.
Example: Calculate Total Marks
const samadhanMarks = 80;
const pradnyaMarks = 90;
const totalMarks = samadhanMarks + pradnyaMarks;
console.log("Samadhan's Marks:", samadhanMarks);
console.log("Pradnya's Marks:", pradnyaMarks);
console.log("Combined Total:", totalMarks);
Execute the File
node marks.js
Expected Output
Samadhan's Marks: 80
Pradnya's Marks: 90
Combined Total: 170
Explanation
constdeclares a variable binding that cannot be reassigned.samadhanMarksstores the first marks value.pradnyaMarksstores the second marks value.totalMarksstores the sum of both values.- The final statements print the stored values.
6. Execute JavaScript Functions
Functions allow us to organize reusable logic. A function can accept parameters, process values, and return a result.
Example: Calculate Total Fees
function calculateTotalFees(firstInstallment, secondInstallment) {
return firstInstallment + secondInstallment;
}
const samadhanFees = calculateTotalFees(10000, 5000);
const pradnyaFees = calculateTotalFees(12000, 8000);
console.log("Samadhan's Total Fees:", samadhanFees);
console.log("Pradnya's Total Fees:", pradnyaFees);
Execute the Program
node fees.js
Expected Output
Samadhan's Total Fees: 15000
Pradnya's Total Fees: 20000
Code Explanation
calculateTotalFees()defines a reusable function.- The parameters receive the installment values.
returnsends the calculated total back to the caller.- The function is called separately for Samadhan and Pradnya.
7. Understand JavaScript Execution Order
JavaScript normally executes synchronous statements in order. Understanding this order helps us predict the program's output.
Example
console.log("Step 1");
const number = 10;
console.log("Step 2");
const result = number * 2;
console.log("Result:", result);
console.log("Step 3");
Expected Output
Step 1
Step 2
Result: 20
Step 3
Execution Flow Diagram
8. Run Different JavaScript Files
A project can contain multiple JavaScript files. You can execute a specific file by passing its name to the Node.js command.
Example Project Structure
NodeJsPractice/
├── app.js
├── marks.js
└── fees.js
Run the First File
node app.js
Run the Second File
node marks.js
Run the Third File
node fees.js
9. Common JavaScript Execution Errors
| Error | Possible Reason | Solution |
|---|---|---|
| Node.js is not recognized | Node.js is unavailable in the current terminal environment. | Check the installation and PATH configuration. |
| Cannot find module or file | The filename or file path is incorrect. | Verify the file name and current directory. |
| SyntaxError | The JavaScript contains invalid syntax. | Check brackets, quotation marks, and statement structure. |
| ReferenceError | The code refers to a variable that is not defined in the current scope. | Check the variable name and declaration. |
| Unexpected output | The saved code or input values differ from what was expected. | Save the file and check the program statements. |
10. CIIT Training Institute - Practice Task
Task: Create a Student Result Program
Create a file named studentResult.js and
complete the following tasks:
- Store the names Samadhan and Pradnya in variables.
- Store marks for three subjects for each student.
- Calculate each student's total marks.
- Calculate each student's average marks.
- Display the student names, totals, and averages.
- Run the program using
node studentResult.js.
Sample Solution
const samadhan = {
name: "Samadhan",
marks: [80, 75, 85]
};
const pradnya = {
name: "Pradnya",
marks: [90, 88, 92]
};
function calculateTotal(marks) {
return marks.reduce((total, mark) => total + mark, 0);
}
function displayResult(student) {
const total = calculateTotal(student.marks);
const average = total / student.marks.length;
console.log("Student:", student.name);
console.log("Total:", total);
console.log("Average:", average);
console.log("--------------------");
}
displayResult(samadhan);
displayResult(pradnya);
Expected Output
Student: Samadhan
Total: 240
Average: 80
--------------------
Student: Pradnya
Total: 270
Average: 90
--------------------
This exercise combines variables, arrays, objects, functions, calculations, and console output in a single Node.js program.
Summary
Running JavaScript in Node.js involves creating a JavaScript file, saving the code, opening a terminal in the correct directory, and executing the file with the node command. We learned how to print messages, use variables, perform calculations, execute functions, understand statement order, run multiple files, and troubleshoot common errors. Practical exercises at CIIT TRAINING INSTITUTE help students develop confidence in writing and executing JavaScript programs.