Node.js is a popular JavaScript runtime built on Chrome’s V8 JavaScript engine. It allows developers to run JavaScript on the server-side, enabling the creation of fast and scalable web applications. In this article, we’ll guide you through the process of creating your first Node.js app: a simple “Hello, World!” program.
Table of contents
Prerequisites
Before getting started, ensure that you have Node.js installed on your system. If you haven’t installed it yet, you can refer to our previous article on How to Install Node.js on Debian 12: A Step-by-Step Guide. Additionally you can check their website: https://nodejs.org/en
Step 1: Create a New Directory
Begin by creating a new directory for your project. Open your terminal and run the following commands:
mkdir hello-world
cd hello-world
Step 2: Initialize a New Node.js Project
Inside the hello-world
directory, initialize a new Node.js project by running the following command and follow the steps provided on your screen:
npm init -y
This command creates a package.json
file with default configurations. The package.json
file serves as a manifest for your Node.js project, containing metadata and dependencies.
Step 3: Create the JavaScript File
Create a new file named app.js
in the hello-world
directory using your preferred text editor. For example, you can use nano
:
nano app.js
Step 4: Write the Node.js Code
In the app.js
file, add the following code:
console.log("Hello, World!");
This line of code uses the console.log()
function to print the string “Hello, World!” to the console.
Save the file and exit the text editor.
Step 5: Run the Node.js App
To run your app, use the following command in the terminal:
node app.js
Node.js will execute the app.js
file, and you should see the output:
Hello, World!
Congratulations! You’ve successfully created and run your first Node.js app.
Conclusion
Creating a basic app is a straightforward process. With a few simple steps, you can have a program up and running, printing “Hello, World!” to the console. This example serves as a starting point for building more complex Node.js applications.
As you continue your Node.js journey, be sure to explore the vast ecosystem of packages and frameworks available through npm (Node Package Manager). Node.js has a thriving community and extensive documentation that can help you along the way.