A Beginner's Journey with Node.js: Writing Your First Code

A Beginner's Journey with Node.js: Writing Your First Code

In the exciting world of software development, Node.js stands out as a powerful tool for building fast and scalable applications. If you're new to Node.js, this guide will help you get started by walking you through installing Node.js, verifying its installation, and writing your first code.

Installing Node.js

Before you start coding, you need to install Node.js on your system. You can download the latest version from the official Node.js website at nodejs.org. Follow the installation prompts for your operating system.

Verifying the Installation

Once Node.js is installed, it's essential to verify everything is set up correctly. Open your terminal and type the following commands:

node -v

This command will display the installed version of Node.js. If it's not installed correctly, you'll see an error message.

Similarly, to check the version of Node Package Manager (NPM), use:

npm -v

This will display the current version of NPM, a package manager that comes with Node.js.

Writing Code in Node.js

Using Node REPL

Node.js offers a Read-Evaluate-Print Loop (REPL) environment, allowing you to execute code directly in the terminal. Start the REPL by typing node in the terminal. You can then write and execute JavaScript code interactively.

However, for more extensive projects, writing code directly in the terminal can be cumbersome. It's better to use an integrated development environment (IDE) like Visual Studio Code (VSCode).

Setting Up a Project in VSCode

  1. Create a Folder: Start by creating a new folder for your project, e.g., my-nodejs-project.

  2. Open the Folder in VSCode: Open VSCode and go to File > Open Folder, selecting your project folder.

  3. Create a New File: Inside your project folder in VSCode, create a file named app.js.

  4. Write Code: Open app.js and write the following simple code:

     let name = "Node JS 03";
     let a = 5;
     let b = 10;
     let c = a + b;
     console.log(name);
     console.log(c);
    
  5. Run the Code: Open the terminal in VSCode (using the shortcut Ctrl + ``) and type node app.js` to run your code.

Understanding Global Objects in Node.js

Node.js has a global object, global, similar to the window object in browsers. This object provides various functionalities like setTimeout(), setInterval(), and more. It's important to note that in Node.js, globalThis is used to refer to the global object consistently across different environments.

By understanding these basic concepts and practicing, you'll build a solid foundation in Node.js, setting the stage for developing more complex applications in the future.