Easy Steps to Begin Working with Node.js

Node.js — A wrapper around V8 with built-in modules providing rich features through easy-to-use asynchronous APIs.

Why Node —

  1. Wrapper around V8

  2. Built-in modules (fs, http, crypto, zip, …)

  3. Asynchronous APIs (no threads)

  4. Debugger and other utilities

  5. NPM

  6. Module dependency manager

Node is the most popular platform for tools. Node ships with reliable package manager (NPM) and module dependency manager (CommonJS modules and ECMAScript modules). Node comes with first-class support and easy API’s for many asynchronous operations like reading ang writing files, consuming data over the network and even compressing and encrypting data. All these operations are asynchronous and execute without blocking the main execution thread.

// Import the http module, which is included with Node.js, to create an HTTP server
const http = require('http');

// Define the hostname and port the server will listen on
const hostname = '127.0.0.1'; // Commonly used as the local host address
const port = 3000; // Port number where the server will be accessible

// Create an HTTP server instance
// The function passed as an argument is the request handler,
// executed every time the server receives a request
const server = http.createServer((req, res) => {
  // Set the HTTP response status code and content type headers
  res.statusCode = 200; // Status code 200 indicates that the request was successful
  res.setHeader('Content-Type', 'text/plain'); 
  // Content-Type header tells the client what content type to expect

  // Send the response body "Hello, World!" and end the response
  res.end('Hello, World!\n');
});

// Make the server listen on the specified hostname and port
server.listen(port, hostname, () => {
  // This callback function is executed once the server starts successfully
  console.log(`Server running at http://${hostname}:${port}/`); 
  // Log a message that the server is running and where it can be accessed
});

In order to use ECMAScript module we can update the file extension from .js to .mjs. As soon you update the extension and try to run the code it will throw error as ReferenceError: require is not defined To fix it we need to use import http from ‘http’. Also we can import named export as import { createServer } from ‘http‘.

How to start a server?

  • Write your JavaScript code in a file with a .js extension, for example, app.js.

  • Navigate to the directory containing your file.

  • Run the code using the command node app.js in the command line.

  • This starts the Node.js runtime and executes the code in app.js.

  • Alternatively, enter the interactive Read-Eval-Print Loop (REPL) by typing node in the command line.

  • In REPL, you can enter and run JavaScript commands immediately for testing or experimentation.

  • Both methods allow you to run and test Node.js applications, whether as a standalone script or through direct interactive input.