Node.js Basics: Getting Started Guide

Node.js Expert 8 min read Basics 1,520 views
Node.js Basics Tutorial Cover Image

What is Node.js?

Node.js is a JavaScript runtime built on Chrome's V8 JavaScript engine. It allows you to run JavaScript on the server-side, opening up new possibilities for web development. Unlike traditional JavaScript that runs in browsers, Node.js enables JavaScript to execute on the server, making it possible to build scalable network applications.

Why Use Node.js?

Node.js has become incredibly popular for several reasons:

  • Fast Performance: Built on V8 engine, Node.js offers excellent performance and speed
  • Single Language: Use JavaScript for both frontend and backend development
  • NPM Ecosystem: Access to npm, the largest package registry with millions of packages
  • Scalability: Perfect for building scalable applications with its event-driven architecture
  • Large Community: Active community providing endless resources and support

Installing Node.js

Getting started with Node.js is straightforward. Follow these steps to install Node.js on your system:

Step 1: Download Node.js

Visit the official Node.js website at nodejs.org and download the LTS (Long Term Support) version for your operating system. The LTS version is recommended for most users as it provides stability and long-term support.

Step 2: Install Node.js

Run the installer and follow the installation wizard. The installer will automatically install both Node.js and npm (Node Package Manager).

Step 3: Verify Installation

Open your terminal or command prompt and run these commands to verify the installation:

# Check Node.js version
node --version

# Check npm version
npm --version

If you see version numbers displayed, Node.js is successfully installed on your system.

Your First Node.js Program

Let's create a simple "Hello World" program to verify everything is working correctly:

Step 1: Create a File

Create a new file called hello.js and add the following code:

// hello.js
console.log('Hello, Node.js!');

Step 2: Run the Program

Open your terminal, navigate to the directory where you saved the file, and run:

node hello.js

You should see "Hello, Node.js!" printed in your terminal. Congratulations! You've just run your first Node.js program.

Understanding the Event Loop

The event loop is one of the most important concepts in Node.js. It's what makes Node.js efficient and able to handle many concurrent connections with a single thread.

Here's how the event loop works:

  1. Node.js takes the code you write and executes it
  2. When it encounters asynchronous operations (like file reading or network requests), it offloads them to the system
  3. When the asynchronous operation completes, it's added to a queue
  4. The event loop continuously checks this queue and executes the callbacks when the main thread is free

Creating Your First Server

Let's create a simple HTTP server to understand how Node.js handles web requests:

Step 1: Import HTTP Module

Create a file called server.js and add the following code:

// Import the built-in HTTP module
const http = require('http');

Step 2: Create the Server

// Create a server
const server = http.createServer((req, res) => {
    // Set the response HTTP header with HTTP status and content type
    res.writeHead(200, { 'Content-Type': 'text/plain' });
    
    // Send the response body "Hello, World!"
    res.end('Hello, World!\n');
});

Step 3: Start Listening

// The server listens on port 3000
server.listen(3000, () => {
    console.log('Server running at http://localhost:3000/');
});

Step 4: Run Your Server

node server.js

Now open your web browser and navigate to http://localhost:3000. You should see "Hello, World!" displayed in your browser.

Understanding Modules

Node.js uses a module system to organize code. Each file in Node.js is treated as a module. The require() function is used to import modules, and module.exports is used to export functionality from a module.

Built-in Modules

Node.js comes with several built-in modules:

  • http - For creating HTTP servers and clients
  • fs - For working with the file system
  • path - For working with file and directory paths
  • os - For getting information about the operating system
  • events - For working with events

Creating Your Own Module

Let's create a simple utility module:

Create the Module File

Create a file called utils.js:

// utils.js
function greet(name) {
    return `Hello, ${name}!`;
}

function add(a, b) {
    return a + b;
}

// Export the functions
module.exports = {
    greet,
    add
};

Use the Module

Create a file called app.js:

// app.js
const utils = require('./utils');

console.log(utils.greet('Alice')); // Output: Hello, Alice!
console.log(utils.add(5, 3));      // Output: 8

Working with NPM

NPM (Node Package Manager) is the package manager for Node.js. It allows you to install and manage third-party packages and dependencies for your projects.

Installing Packages

To install a package, use the npm install command:

# Install a package locally
npm install express

# Install a package globally
npm install -g nodemon

# Install multiple packages
npm install express mongoose cors

Package.json

The package.json file is the heart of any Node.js project. It contains metadata about your project and lists dependencies:

{
  "name": "my-node-app",
  "version": "1.0.0",
  "description": "A simple Node.js application",
  "main": "app.js",
  "scripts": {
    "start": "node app.js",
    "dev": "nodemon app.js"
  },
  "dependencies": {
    "express": "^4.18.2"
  },
  "devDependencies": {
    "nodemon": "^2.0.20"
  }
}

Asynchronous Programming

Node.js is built around asynchronous programming. Understanding how to work with asynchronous code is crucial for Node.js development.

Callbacks

Callbacks are the traditional way to handle asynchronous operations in Node.js:

const fs = require('fs');

// Read a file asynchronously
fs.readFile('example.txt', 'utf8', (err, data) => {
    if (err) {
        console.error('Error reading file:', err);
        return;
    }
    console.log('File content:', data);
});

Promises

Promises provide a cleaner way to handle asynchronous operations:

const fs = require('fs').promises;

// Read a file using promises
fs.readFile('example.txt', 'utf8')
    .then(data => {
        console.log('File content:', data);
    })
    .catch(err => {
        console.error('Error reading file:', err);
    });

Async/Await

Async/await is the modern way to handle asynchronous operations, making code look synchronous:

const fs = require('fs').promises;

async function readFile() {
    try {
        const data = await fs.readFile('example.txt', 'utf8');
        console.log('File content:', data);
    } catch (err) {
        console.error('Error reading file:', err);
    }
}

readFile();

Next Steps

Now that you understand the basics of Node.js, you can explore more advanced topics:

Conclusion

Node.js opens up exciting possibilities for JavaScript developers. With its fast performance, extensive ecosystem, and active community, it's an excellent choice for building modern web applications. This guide covers the fundamentals you need to get started, but there's much more to explore as you continue your Node.js journey.