Node.js Get Started

Node.js is a powerful JavaScript runtime built on Chrome’s V8 engine that allows you to run JavaScript on the server side. In this guide, we’ll walk you through getting started with Node.js from installation to building your first basic application.


1. What is Node.js?

Node.js is an open-source, cross-platform runtime environment that executes JavaScript code outside of a browser. It’s widely used for server-side development, allowing developers to create fast, scalable network applications.

Key features include:

  • Asynchronous and Event-Driven: Non-blocking I/O operations make it highly efficient for handling multiple tasks simultaneously.
  • Single Programming Language: You can use JavaScript for both client-side and server-side development.
  • Fast Execution: Powered by Google’s V8 engine, Node.js executes JavaScript code at lightning speed.
  • Large Ecosystem: The NPM (Node Package Manager) provides access to thousands of open-source libraries.

2. Installing Node.js

Before diving into development, you need to install Node.js on your machine.

2.1. Installation on Windows and macOS

  • Go to the Node.js official website and download the latest version (LTS recommended).
  • Run the installer and follow the setup instructions.
  • After installation, open a terminal or command prompt and verify the installation:
  node -v
  npm -v

This will display the installed versions of Node.js and NPM.

2.2. Installation on Linux

To install Node.js on Linux (Debian/Ubuntu):

sudo apt update
sudo apt install nodejs
sudo apt install npm

Verify installation using:

node -v
npm -v

3. Understanding NPM (Node Package Manager)

NPM comes bundled with Node.js and is used to manage packages (libraries) that extend the functionality of your Node.js application.

3.1 Basic NPM Commands

  • Install a Package Locally: Packages are installed in the project folder.
  npm install <package-name>
  • Install a Package Globally: Installs the package for use across your system.
  npm install -g <package-name>
  • Uninstalling Packages:
  npm uninstall <package-name>

3.2 Exploring Packages

You can search for packages on the official NPM registry. Some commonly used packages include:

  • Express.js: A minimal web framework for building APIs and web apps.
  • Lodash: A utility library for simplifying JavaScript code.

4. Writing Your First Node.js Application

Let’s start by creating a simple Node.js application to get familiar with the basics.

4.1 Create a “Hello World” Application

  1. Create a new file app.js:
   // app.js
   console.log('Hello, Node.js!');
  1. Run the script:
   node app.js

This will print Hello, Node.js! in your terminal.

4.2 Creating a Simple Web Server

Node.js is often used to create web servers. Let’s create a simple server that responds with “Hello, World!” when accessed.

  1. Create a new file server.js:
   // server.js
   const http = require('http');

   const server = http.createServer((req, res) => {
     res.statusCode = 200;
     res.setHeader('Content-Type', 'text/plain');
     res.end('Hello, World!\n');
   });

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

The HTTP module in Node.js is a built-in library that allows developers to create web applications and services

  • Create web servers: Set up a server that listens for HTTP requests on a given port 
  • Handle requests and responses: Process incoming data and send responses back to clients 
  • Communicate with other APIs: Use HTTP 1.1, HTTP 2, and HTTPS to communicate with other APIs 
  • Work with headers: Set up headers and status code, either implicitly or explicitly 
  1. Run the server:
   node server.js
  1. Open your browser and go to http://localhost:3000/. You should see the message “Hello, World!” displayed.

5. Working with Modules

Node.js applications are composed of modules. You can use built-in modules (like http, fs, path) or create your own.

5.1 Creating Custom Modules

  1. Create a file math.js:
   // math.js
   function add(a, b) {
     return a + b;
   }

   module.exports = add;
  1. Use this module in your application:
   // app.js
   const add = require('./math');
   console.log(add(5, 10)); // Output: 15

6. Using Third-Party Modules

Node.js can easily incorporate third-party modules via NPM. Let’s install the express module, which simplifies web development.

  1. Install Express:
   npm install express
  1. Create a new file express-server.js:
   // express-server.js
   const express = require('express');
   const app = express();

   app.get('/', (req, res) => {
     res.send('Hello from Express!');
   });

   app.listen(3000, () => {
     console.log('Express server running at http://localhost:3000/');
   });
  1. Run the server:
   node express-server.js
  1. Visit http://localhost:3000/ in your browser, and you should see “Hello from Express!”.

7. Asynchronous Programming in Node.js

Node.js is inherently asynchronous, meaning it can handle multiple operations simultaneously without waiting for one to finish. You can use callbacks, promises, and async/await to handle asynchronous operations.

7.1 Using Callbacks

const fs = require('fs');

fs.readFile('file.txt', 'utf8', (err, data) => {
  if (err) throw err;
  console.log(data);
});

7.2 Using Promises

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

fs.readFile('file.txt', 'utf8')
  .then(data => console.log(data))
  .catch(err => console.error(err));

7.3 Using Async/Await

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

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

readFile();

8. Conclusion and Next Steps

Now that you’ve created your first Node.js application and explored some key concepts, here are some next steps:

  • Explore Express.js to create more complex web applications.
  • Learn more about asynchronous programming in Node.js.
  • Dive into databases (e.g., MongoDB, MySQL) integration with Node.js.
  • Explore real-time applications using Socket.IO.

With Node.js, you can build anything from small utilities to large-scale enterprise applications. Keep exploring the vast ecosystem of libraries and frameworks to harness the full potential of Node.js.

Node.js Get Started

Node.js is a powerful JavaScript runtime built on Chrome’s V8 engine that allows you to run JavaScript on the server side. In this guide, we’ll walk you through getting started with Node.js from installation to building your first basic application.


1. What is Node.js?

Node.js is an open-source, cross-platform runtime environment that executes JavaScript code outside of a browser. It’s widely used for server-side development, allowing developers to create fast, scalable network applications.

Key features include:

  • Asynchronous and Event-Driven: Non-blocking I/O operations make it highly efficient for handling multiple tasks simultaneously.
  • Single Programming Language: You can use JavaScript for both client-side and server-side development.
  • Fast Execution: Powered by Google’s V8 engine, Node.js executes JavaScript code at lightning speed.
  • Large Ecosystem: The NPM (Node Package Manager) provides access to thousands of open-source libraries.

2. Installing Node.js

Before diving into development, you need to install Node.js on your machine.

2.1. Installation on Windows and macOS

  • Go to the Node.js official website and download the latest version (LTS recommended).
  • Run the installer and follow the setup instructions.
  • After installation, open a terminal or command prompt and verify the installation:
  node -v
  npm -v

This will display the installed versions of Node.js and NPM.

2.2. Installation on Linux

To install Node.js on Linux (Debian/Ubuntu):

sudo apt update
sudo apt install nodejs
sudo apt install npm

Verify installation using:

node -v
npm -v

3. Understanding NPM (Node Package Manager)

NPM comes bundled with Node.js and is used to manage packages (libraries) that extend the functionality of your Node.js application.

3.1 Basic NPM Commands

  • Install a Package Locally: Packages are installed in the project folder.
  npm install <package-name>
  • Install a Package Globally: Installs the package for use across your system.
  npm install -g <package-name>
  • Uninstalling Packages:
  npm uninstall <package-name>

3.2 Exploring Packages

You can search for packages on the official NPM registry. Some commonly used packages include:

  • Express.js: A minimal web framework for building APIs and web apps.
  • Lodash: A utility library for simplifying JavaScript code.

4. Writing Your First Node.js Application

Let’s start by creating a simple Node.js application to get familiar with the basics.

4.1 Create a “Hello World” Application

  1. Create a new file app.js:
   // app.js
   console.log('Hello, Node.js!');
  1. Run the script:
   node app.js

This will print Hello, Node.js! in your terminal.

4.2 Creating a Simple Web Server

Node.js is often used to create web servers. Let’s create a simple server that responds with “Hello, World!” when accessed.

  1. Create a new file server.js:
   // server.js
   const http = require('http');

   const server = http.createServer((req, res) => {
     res.statusCode = 200;
     res.setHeader('Content-Type', 'text/plain');
     res.end('Hello, World!\n');
   });

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

The HTTP module in Node.js is a built-in library that allows developers to create web applications and services

  • Create web servers: Set up a server that listens for HTTP requests on a given port 
  • Handle requests and responses: Process incoming data and send responses back to clients 
  • Communicate with other APIs: Use HTTP 1.1, HTTP 2, and HTTPS to communicate with other APIs 
  • Work with headers: Set up headers and status code, either implicitly or explicitly 
  1. Run the server:
   node server.js
  1. Open your browser and go to http://localhost:3000/. You should see the message “Hello, World!” displayed.

5. Working with Modules

Node.js applications are composed of modules. You can use built-in modules (like http, fs, path) or create your own.

5.1 Creating Custom Modules

  1. Create a file math.js:
   // math.js
   function add(a, b) {
     return a + b;
   }

   module.exports = add;
  1. Use this module in your application:
   // app.js
   const add = require('./math');
   console.log(add(5, 10)); // Output: 15

6. Using Third-Party Modules

Node.js can easily incorporate third-party modules via NPM. Let’s install the express module, which simplifies web development.

  1. Install Express:
   npm install express
  1. Create a new file express-server.js:
   // express-server.js
   const express = require('express');
   const app = express();

   app.get('/', (req, res) => {
     res.send('Hello from Express!');
   });

   app.listen(3000, () => {
     console.log('Express server running at http://localhost:3000/');
   });
  1. Run the server:
   node express-server.js
  1. Visit http://localhost:3000/ in your browser, and you should see “Hello from Express!”.

7. Asynchronous Programming in Node.js

Node.js is inherently asynchronous, meaning it can handle multiple operations simultaneously without waiting for one to finish. You can use callbacks, promises, and async/await to handle asynchronous operations.

7.1 Using Callbacks

const fs = require('fs');

fs.readFile('file.txt', 'utf8', (err, data) => {
  if (err) throw err;
  console.log(data);
});

7.2 Using Promises

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

fs.readFile('file.txt', 'utf8')
  .then(data => console.log(data))
  .catch(err => console.error(err));

7.3 Using Async/Await

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

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

readFile();

8. Conclusion and Next Steps

Now that you’ve created your first Node.js application and explored some key concepts, here are some next steps:

  • Explore Express.js to create more complex web applications.
  • Learn more about asynchronous programming in Node.js.
  • Dive into databases (e.g., MongoDB, MySQL) integration with Node.js.
  • Explore real-time applications using Socket.IO.

With Node.js, you can build anything from small utilities to large-scale enterprise applications. Keep exploring the vast ecosystem of libraries and frameworks to harness the full potential of Node.js.