bf-workflows

Node.js

What is Node.js?

Node.js is a powerful and versatile open-source runtime environment for executing JavaScript code on the server side. It enables developers to build scalable network applications with ease.

Key Features of Node.js

Core Concepts

1. Asynchronous Programming

Node.js utilizes an asynchronous, non-blocking I/O model, which helps in building highly scalable applications.

const fs = require("fs");

// Non-blocking asynchronous read
fs.readFile("example.txt", "utf8", (err, data) => {
  if (err) throw err;
  console.log(data);
});

console.log("This will log before the file content.");

2. Event Loop

The event loop is a core feature of Node.js that manages and dispatches events or messages. It allows Node.js to perform non-blocking operations.

const EventEmitter = require("events");
const myEmitter = new EventEmitter();

myEmitter.on("event", () => {
  console.log("An event occurred!");
});

myEmitter.emit("event");

3. NPM (Node Package Manager)

NPM is the default package manager for Node.js, which hosts thousands of libraries and tools for Node.js development.

4. Modules

Node.js uses modules to organize code into reusable components. There are built-in modules, third-party modules, and custom modules.

Getting Started with Node.js

1. Install Node.js

Download and install Node.js from the official website. The installation includes NPM.

2. Verify Installation

Check the installed versions of Node.js and NPM:

node -v
npm -v

3. Create Your First Node.js Application

Create a file named app.js with the following content:

console.log("Hello, Node.js!");

Run the application:

node app.js

4. Create a Simple Web Server

Create a file named server.js with the following content:

const http = require("http");

const hostname = "127.0.0.1";
const port = 3000;

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

server.listen(port, hostname, () => {
  console.log(`Server running at http://${hostname}:${port}/`);
});

Run the server:

node server.js

Visit http://127.0.0.1:3000/ in your web browser to see “Hello World”.

Advanced Topics

1. Express.js

Express.js is a popular web framework for Node.js, designed for building web applications and APIs.

2. Asynchronous Programming with Promises and Async/Await

Promises and async/await are modern JavaScript features for handling asynchronous operations.

Resources