Getting Started with Nodejs

RMAG news

Node.js, built on Chrome’s V8 JavaScript Engine, is a powerful JavaScript runtime that extends its capabilities to the server-side. Its asynchronous, event-driven nature, coupled with a non-blocking IO model, makes it exceptionally fast and efficient.

Understanding Node.js

Node.js operates on an event-driven architecture, initializing all variables and functions and waiting for events to occur. Its asynchronous nature ensures that it doesn’t block itself for one request but moves swiftly to the next, enhancing performance.

Getting Started

Let’s walk through creating a simple Node.js application step by step. We’ll create a basic web server using Express.js and render a dynamic webpage using Handlebars as the templating engine.

Step 1: Set Up Your Project

Create a new directory for your project and navigate into it:

mkdir my-node-app
cd my-node-app

Initialize a new Node.js project:

npm init -y

This will create a package.json file with default settings.

Step 2: Install Dependencies

Install Express.js and Handlebars as dependencies:

npm install express hbs

Step 3: Create Your Server

Create a file named app.js in your project directory and open it in your code editor.

// Import required modules
const express = require(‘express’);
const hbs = require(‘hbs’);
const path = require(‘path’);

// Create an Express app
const app = express();

// Set the view engine to Handlebars
app.set(‘view engine’, ‘hbs’);

// Set the path for views and partials
app.set(‘views’, path.join(__dirname, ‘views’));
hbs.registerPartials(path.join(__dirname, ‘views’, ‘partials’));

// Define routes
app.get(‘/’, (req, res) => {
// Render the index page with dynamic data
res.render(‘index’, {
title: ‘Home’,
author: ‘Your Name’
});
});

// Start the server
app.listen(3000, () => {
console.log(‘Server is running on port 3000’);
});

Step 4: Create Your Views

Create a directory named views in your project directory. Inside this directory, create two files: index.hbs and partials/header.hbs.

File: index.hbs

<!DOCTYPE html>
<html>
<head>
<title>{{ title }}</title>
</head>
<body>
{{>partials/header}}
<h1>Welcome to {{ title }}</h1>
<p>Written by {{ author }}</p>
</body>
</html>
partials/header.hbs:

File: partials/header.hbs:

<header>
<h1>My Node.js App</h1>
<nav>
<ul>
<li><a href=”/”>Home</a></li>
</ul>
</nav>
</header>

Step 5: Run Your Application

Navigate to your project directory in the terminal and run your Node.js application:

node app.js

Visit http://localhost:3000 in your web browser to see your Node.js application in action.

That’s it! You’ve created a simple Node.js application with Express.js and Handlebars. Feel free to expand upon this example by adding more routes, views, or functionality as needed.