In this lesson, we will write our first JavaScript program and run it using Node.js in the terminal.
Node.js allows us to execute JavaScript code outside a web browser.
We can create a JavaScript file, write code inside it, and execute
that file using the node command.
node -v in your terminal.
console.log().First, create a folder on your computer to store your Node.js programs.
Create a folder named:
MyNodeProject
You can create this folder on your Desktop or in any other convenient location.
Open the project folder in a code editor such as Visual Studio Code.
Create a new file named app.js.
MyNodeProject/
└── app.js
.js
extension. Do not accidentally save it as app.js.txt.
Write the following code inside the app.js file.
console.log("Hello, Node.js!");
Hello, Node.js!
console provides methods for displaying messages and other information.log() displays the supplied information in the terminal."Hello, Node.js!" is the text we want to display.To run your program, open a terminal in the project folder.
MyNodeProject folder in VS Code.
You can also use Command Prompt or another terminal, provided it is
opened in the folder containing app.js.
Type the following command in the terminal:
node app.js
Hello, Node.js!
We can use multiple console.log() statements to display
multiple lines of output.
console.log("Welcome to Node.js");
console.log("I am learning JavaScript");
console.log("This is my first program");
Welcome to Node.js
I am learning JavaScript
This is my first program
Variables store values that we can use in our programs. We can declare
variables using let or const.
let name = "Rahul";
let age = 20;
let course = "Node.js";
console.log("Name:", name);
console.log("Age:", age);
console.log("Course:", course);
Name: Rahul
Age: 20
Course: Node.js
let name = "Rahul"; stores a name in a variable.let age = 20; stores a number.let course = "Node.js"; stores a course name.console.log() displays the labels and variable values.Node.js can execute JavaScript arithmetic expressions just like a browser.
let a = 10;
let b = 20;
let sum = a + b;
console.log("Sum:", sum);
Sum: 30
Modify the following example to display your own name and city.
const studentName = "Amit";
const city = "Aurangabad";
console.log("My name is " + studentName);
console.log("I live in " + city);
My name is Amit
I live in Aurangabad
"Amit" to
your name and "Aurangabad" to your city. Save the file
and run node app.js again.
If Node.js cannot find app.js, check the file
name and make sure the terminal is in the correct folder.
Make sure the file is named app.js, not
app.js.txt.
Incorrect code:
console.log("Hello, Node.js!);
Correct code:
console.log("Hello, Node.js!");
The opening and closing quotation marks must match.
app.js.console.log().node app.js..js file, save it,
and use node filename.js to execute it.
1. Which command runs a file named app.js?
2. Which function displays a message in the terminal?
3. Which file extension is commonly used for JavaScript files?